ViewController.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. // Copyright (C) 2016 Inigo Valentin
  2. //
  3. // This file is part of the Gasteizko Margolariak IOS app.
  4. //
  5. // The Gasteizko Margolariak IOS app is free software: you can
  6. // redistribute it and/or modify it under the terms of the
  7. // GNU General Public License as published by the Free Software
  8. // Foundation, either version 3 of the License, or (at your
  9. // option) any later version.
  10. //
  11. // The Gasteizko Margolariak IOS app is distributed in the
  12. // hope that it will be useful, but WITHOUT ANY WARRANTY;
  13. // without even the implied warranty of MERCHANTABILITY or
  14. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
  15. // Public License for more details.
  16. //
  17. // You should have received a copy of the GNU General Public
  18. // License along with the Gasteizko Margolariak IOS app.
  19. // If not, see <http://www.gnu.org/licenses/>.
  20. import UIKit
  21. import CoreData
  22. import CoreLocation
  23. /**
  24. The view controller of the app.
  25. */
  26. class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIGestureRecognizerDelegate, CLLocationManagerDelegate {
  27. var delegate: AppDelegate?
  28. //The menu collection.
  29. var sectionCollection: UICollectionView!
  30. // Need to save the sync segue.
  31. var syncSegue: UIStoryboardSegue?
  32. //Each of the sections of the app.
  33. @IBOutlet var containerViewGallery: GalleryView!
  34. @IBOutlet var containerViewBlog: BlogView!
  35. @IBOutlet var containerViewActivities: ActivitiesView!
  36. @IBOutlet var containerViewLablanca: LablancaView!
  37. @IBOutlet var containerViewLocation: LocationView!
  38. @IBOutlet var containerViewHome: HomeView!
  39. // Passed id to perform segues.
  40. var passId: Int = -1
  41. var passAlbum: Int = -1
  42. // Location-related variables.
  43. var locationManager = CLLocationManager()
  44. var didFindMyLocation = false
  45. var locationTimer: Timer? = nil
  46. /**
  47. Controller initializer.
  48. :param: coder Coder.
  49. */
  50. required init?(coder aDecoder: NSCoder) {
  51. NSLog(":CONTROLLER:DEBUG: Init!")
  52. super.init(coder: aDecoder)
  53. }
  54. func getLocation() -> CLLocationCoordinate2D {
  55. return (locationManager.location?.coordinate)!
  56. }
  57. /**
  58. Retrieves the application context.
  59. :return: The application context.
  60. */
  61. func getContext () -> NSManagedObjectContext {
  62. //let appDelegate = UIApplication.shared.delegate as! AppDelegate
  63. //return appDelegate.persistentContainer.viewContext
  64. return NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
  65. }
  66. /**
  67. Shows a post.
  68. :param: id The post id.
  69. */
  70. func showPost(id: Int){
  71. NSLog(":CONTROLLER:DEBUG: Showing Post \(id)")
  72. self.passId = id
  73. performSegue(withIdentifier: "SeguePost", sender: nil)
  74. }
  75. /**
  76. Shows a past activity.
  77. :param: id The activity id.
  78. */
  79. func showPastActivity(id: Int){
  80. NSLog(":CONTROLLER:DEBUG: Showing past activity \(id)")
  81. self.passId = id
  82. performSegue(withIdentifier: "SeguePastActivity", sender: nil)
  83. }
  84. /**
  85. Shows a future activity.
  86. :param: id The activity id.
  87. */
  88. func showFutureActivity(id: Int){
  89. NSLog(":CONTROLLER:DEBUG: Showing future activity \(id)")
  90. self.passId = id
  91. // TODO
  92. //performSegue(withIdentifier: "SegueFutureActivity", sender: nil)
  93. }
  94. /**
  95. Shows an album.
  96. :param: id The album id.
  97. */
  98. func showAlbum(id: Int){
  99. NSLog(":CONTROLLER:DEBUG: Showing album \(id)")
  100. self.passId = id
  101. performSegue(withIdentifier: "SegueAlbum", sender: nil)
  102. }
  103. // TODO: This must go in it AlbumViewController
  104. /**
  105. Shows a photo.
  106. :param: id The album id.
  107. */
  108. func showPhoto(album: Int, photo: Int){
  109. NSLog(":CONTROLLER:DEBUG: Showing photo \(photo) of album \(album)")
  110. self.passAlbum = album
  111. self.passId = photo
  112. performSegue(withIdentifier: "SeguePhoto", sender: nil)
  113. NSLog(":CONTROLLER:DEBUG: PHOTO should be shown")
  114. }
  115. /**
  116. Shows a schedule.
  117. :param: margolari True for the margolari schedule, false for the city one.
  118. */
  119. func showSchedule(margolari: Bool){
  120. NSLog(":CONTROLLER:DEBUG: Showing schedule. Margolari: \(margolari)")
  121. if margolari == true{
  122. self.passId = 1
  123. }
  124. else{
  125. self.passId = 0
  126. }
  127. performSegue(withIdentifier: "SegueSchedule", sender: nil)
  128. }
  129. /** m
  130. Handles the initial sync process.
  131. It can start it, showing the sync screen, or finish it, hidding the screen.
  132. :param: showScreen True to start the sync, false to end it.
  133. */
  134. func initialSync(showScreen: Bool){
  135. if showScreen == true{
  136. NSLog(":CONTROLLER:DEBUG: Showing initial sync screen.")
  137. performSegue(withIdentifier: "SegueSync", sender: nil)
  138. Sync(synchronous: true)
  139. }
  140. else{
  141. NSLog(":CONTROLLER:DEBUG: Re-populating views and hidding initial sync screen.")
  142. NSLog(":CONTROLLER:DEBUG: Re-populating disabled: Throws error.")
  143. //self.populate()
  144. syncSegue?.destination.dismiss(animated: true, completion: nil)
  145. }
  146. }
  147. /**
  148. Run before performing a segue.
  149. Assigns id if neccessary.
  150. :param: segue The segue to perform.
  151. :sender: The calling view.
  152. */
  153. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  154. NSLog(":CONTROLLER:DEBUG: preparing for segue '\(String(describing: segue.identifier))' with id \(self.passId)")
  155. if segue.identifier == "SeguePost"{
  156. (segue.destination as! PostViewController).id = passId
  157. }
  158. if segue.identifier == "SegueAlbum"{
  159. (segue.destination as! AlbumViewController).id = passId
  160. }
  161. if segue.identifier == "SeguePhoto"{
  162. (segue.destination as! PhotoViewController).photoId = passId
  163. (segue.destination as! PhotoViewController).albumId = passAlbum
  164. }
  165. if segue.identifier == "SegueSchedule"{
  166. if passId == 1{
  167. (segue.destination as! ScheduleViewController).margolari = true
  168. }
  169. else{
  170. (segue.destination as! ScheduleViewController).margolari = false
  171. }
  172. }
  173. if segue.identifier == "SegueSync"{
  174. self.syncSegue = segue
  175. }
  176. if segue.identifier == "SeguePastActivity"{
  177. (segue.destination as! PastActivityViewController).id = passId
  178. }
  179. if segue.identifier == "SegueFutureActivity"{
  180. // TODO
  181. //(segue.destination as! FutureActivityViewController).id = passId
  182. }
  183. }
  184. override func viewWillAppear(_ animated: Bool) {
  185. NSLog(":CONTROLLER:DEBUG: Forcing a call to populate")
  186. self.populate()
  187. super.viewWillAppear(animated)
  188. }
  189. /**
  190. Run when the app loads.
  191. */
  192. override func viewDidLoad() {
  193. // Ask for location permissions.
  194. locationManager.delegate = self
  195. locationManager.requestWhenInUseAuthorization()
  196. //Hide all sections, except for the first one
  197. self.containerViewLocation.alpha = 0
  198. self.containerViewLablanca.alpha = 0
  199. self.containerViewActivities.alpha = 0
  200. self.containerViewBlog.alpha = 0
  201. self.containerViewGallery.alpha = 0
  202. // Start the location schedule
  203. fetchLocation()
  204. self.locationTimer = Timer.scheduledTimer(timeInterval: 90, target: self, selector: #selector(fetchLocation), userInfo: nil, repeats: true)
  205. NSLog(":CONTROLLER:DEBUG: Don't skyp sync")
  206. //NSLog(":CONTROLLER:DEBUG: Skyp sync")
  207. Sync()
  208. self.delegate = UIApplication.shared.delegate as? AppDelegate
  209. self.delegate?.controller = self
  210. //self.sectionCollection.visibleCells[0].isSelected = true
  211. super.viewDidLoad()
  212. }
  213. func fetchLocation(){
  214. FetchLocation()
  215. }
  216. /**
  217. Actually populates all sections.
  218. As of now, not working.
  219. */
  220. func populate(){
  221. if (self.containerViewHome != nil){
  222. //(self.containerViewHome as HomeView).populate()
  223. //let ng = self.containerViewHome.dbgTxt
  224. //NSLog("AAAAA \(ng)")
  225. }
  226. else{
  227. NSLog("CONTROLLER:ERROR: containerViewHome couldn't be populated: It is nil.")
  228. }
  229. //self.containerLocation.populate()
  230. //self.containerLablanca.populate()
  231. //self.containerViewActivities.populate()
  232. //self.containerViewBlog.populate()
  233. //self.containerGallery.populate()
  234. }
  235. /**
  236. Executed when the view is actually shown.
  237. Performs the initial sync in the first run.
  238. It also generates a user id if none exists.
  239. :param: animated Wether the controller appearance must be animated or not.
  240. */
  241. override func viewDidAppear(_ animated: Bool) {
  242. super.viewDidAppear(animated)
  243. if UserDefaults.standard.object(forKey: "userId") == nil{
  244. let newUid = randomString(length: 16)
  245. let defaults = UserDefaults.standard
  246. defaults.set(newUid, forKey: "userId")
  247. initialSync(showScreen: true)
  248. }
  249. }
  250. /**
  251. Generates a random string to be used as a user identifier.
  252. :param: length The length of the generated string.
  253. :return: A random alphanumeric string with the indicated length.
  254. */
  255. func randomString(length: Int) -> String {
  256. let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  257. let len = UInt32(letters.length)
  258. var randomString = ""
  259. for _ in 0 ..< length {
  260. let rand = arc4random_uniform(len)
  261. var nextChar = letters.character(at: Int(rand))
  262. randomString += NSString(characters: &nextChar, length: 1) as String
  263. }
  264. return randomString
  265. }
  266. /**
  267. Dispose of any resources that can be recreated.
  268. */
  269. override func didReceiveMemoryWarning() {
  270. super.didReceiveMemoryWarning()
  271. }
  272. //Menu items.
  273. let reuseIdentifier = "cell"
  274. var selected = 0
  275. var items = ["Home", "Location", "La Blanca", "Actividades", "Blog", "Gallery"]
  276. // MARK: - UICollectionViewDataSource protocol
  277. /**
  278. Sets a collection of menu items.
  279. :param: numberOfItemsInSection The number of entries of the menu.
  280. :return: The number of entries of the menu.
  281. */
  282. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  283. return self.items.count
  284. }
  285. //Make a cell for each section
  286. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  287. var first = true
  288. //Get a reference to our storyboard cell
  289. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MenuCollectionViewCell
  290. //Set text
  291. cell.label.text = self.items[indexPath.item]
  292. // Mark the first one as selected.
  293. if indexPath.item == 0{
  294. cell.isSelected = true
  295. first = false
  296. }
  297. return cell
  298. }
  299. // MARK: - UICollectionViewDelegate protocol
  300. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  301. sectionCollection = collectionView
  302. showComponent(selected: indexPath.item)
  303. }
  304. /**
  305. Caled when an item of the menu bar is selected.
  306. :param: selected Index of the selected item.
  307. */
  308. @IBAction func showComponent(selected: Int) {
  309. NSLog(":CONTROLLER:DEBUG: Selected: \(selected)")
  310. //Activate label
  311. var i = 0
  312. /*for cell in sectionCollection.visibleCells as! [MenuCollectionViewCell]{ //TODO: Not only visibles!
  313. if i == selected + 1{
  314. cell.bar.backgroundColor = UIColor(red: 90/255, green: 180/255, blue: 255/255, alpha: 1)
  315. cell.label.font = UIFont.boldSystemFont(ofSize: cell.label.font.pointSize)
  316. }
  317. else{
  318. cell.bar.backgroundColor = UIColor(red: 148/255, green: 209/255, blue: 255/255, alpha: 1)
  319. cell.label.font = UIFont.systemFont(ofSize: cell.label.font.pointSize)
  320. }
  321. i = i + 1
  322. }*/
  323. //Show the view
  324. if selected == 0 {
  325. UIView.animate(withDuration: 0.5, animations: {
  326. self.containerViewHome.alpha = 1
  327. self.containerViewLocation.alpha = 0
  328. self.containerViewLablanca.alpha = 0
  329. self.containerViewActivities.alpha = 0
  330. self.containerViewBlog.alpha = 0
  331. self.containerViewGallery.alpha = 0
  332. })
  333. }
  334. else if selected == 1 {
  335. UIView.animate(withDuration: 0.5, animations: {
  336. self.containerViewHome.alpha = 0
  337. self.containerViewLocation.alpha = 1
  338. self.containerViewLablanca.alpha = 0
  339. self.containerViewActivities.alpha = 0
  340. self.containerViewBlog.alpha = 0
  341. self.containerViewGallery.alpha = 0
  342. })
  343. }
  344. else if selected == 2 {
  345. UIView.animate(withDuration: 0.5, animations: {
  346. self.containerViewHome.alpha = 0
  347. self.containerViewLocation.alpha = 0
  348. self.containerViewLablanca.alpha = 1
  349. self.containerViewActivities.alpha = 0
  350. self.containerViewBlog.alpha = 0
  351. self.containerViewGallery.alpha = 0
  352. })
  353. }
  354. else if selected == 3 {
  355. UIView.animate(withDuration: 0.5, animations: {
  356. self.containerViewHome.alpha = 0
  357. self.containerViewLocation.alpha = 0
  358. self.containerViewLablanca.alpha = 0
  359. self.containerViewActivities.alpha = 1
  360. self.containerViewBlog.alpha = 0
  361. self.containerViewGallery.alpha = 0
  362. })
  363. }
  364. else if selected == 4 {
  365. UIView.animate(withDuration: 0.5, animations: {
  366. self.containerViewHome.alpha = 0
  367. self.containerViewLocation.alpha = 0
  368. self.containerViewLablanca.alpha = 0
  369. self.containerViewActivities.alpha = 0
  370. self.containerViewBlog.alpha = 1
  371. self.containerViewGallery.alpha = 0
  372. })
  373. }
  374. else if selected == 5 {
  375. UIView.animate(withDuration: 0.5, animations: {
  376. self.containerViewHome.alpha = 0
  377. self.containerViewLocation.alpha = 0
  378. self.containerViewLablanca.alpha = 0
  379. self.containerViewActivities.alpha = 0
  380. self.containerViewBlog.alpha = 0
  381. self.containerViewGallery.alpha = 1
  382. })
  383. }
  384. }
  385. }