ViewController.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. // Location-related variables.
  42. var locationManager = CLLocationManager()
  43. var didFindMyLocation = false
  44. var locationTimer: Timer? = nil
  45. /**
  46. Controller initializer.
  47. :param: coder Coder.
  48. */
  49. required init?(coder aDecoder: NSCoder) {
  50. NSLog(":CONTROLLER:DEBUG: Init!")
  51. super.init(coder: aDecoder)
  52. }
  53. func getLocation() -> CLLocationCoordinate2D {
  54. return (locationManager.location?.coordinate)!
  55. }
  56. /**
  57. Retrieves the application context.
  58. :return: The application context.
  59. */
  60. func getContext () -> NSManagedObjectContext {
  61. //let appDelegate = UIApplication.shared.delegate as! AppDelegate
  62. //return appDelegate.persistentContainer.viewContext
  63. return NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
  64. }
  65. /**
  66. Shows a post.
  67. :param: id The post id.
  68. */
  69. func showPost(id: Int){
  70. NSLog(":CONTROLLER:DEBUG: Showing Post \(id)")
  71. self.passId = id
  72. performSegue(withIdentifier: "SeguePost", sender: nil)
  73. }
  74. /**
  75. Shows an album.
  76. :param: id The album id.
  77. */
  78. func showAlbum(id: Int){
  79. NSLog(":CONTROLLER:DEBUG: Showing album \(id)")
  80. self.passId = id
  81. performSegue(withIdentifier: "SegueAlbum", sender: nil)
  82. }
  83. /**
  84. Shows a schedule.
  85. :param: margolari True for the margolari schedule, false for the city one.
  86. */
  87. func showSchedule(margolari: Bool){
  88. NSLog(":CONTROLLER:DEBUG: Showing schedule. Margolari: \(margolari)")
  89. if margolari == true{
  90. self.passId = 1
  91. }
  92. else{
  93. self.passId = 0
  94. }
  95. performSegue(withIdentifier: "SegueSchedule", sender: nil)
  96. }
  97. /**
  98. Handles the initial sync process.
  99. It can start it, showing the sync screen, or finish it, hidding the screen.
  100. :param: showScreen True to start the sync, false to end it.
  101. */
  102. func initialSync(showScreen: Bool){
  103. if showScreen == true{
  104. NSLog(":CONTROLLER:DEBUG: Showing initial sync screen.")
  105. performSegue(withIdentifier: "SegueSync", sender: nil)
  106. Sync(synchronous: true)
  107. }
  108. else{
  109. NSLog(":CONTROLLER:DEBUG: Re-populating views and hidding initial sync screen.")
  110. NSLog(":CONTROLLER:DEBUG: Re-populating disabled: Throws error.")
  111. //self.populate()
  112. syncSegue?.destination.dismiss(animated: true, completion: nil)
  113. }
  114. }
  115. /**
  116. Run before performing a segue.
  117. Assigns id if neccessary.
  118. :param: segue The segue to perform.
  119. :sender: The calling view.
  120. */
  121. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  122. NSLog(":CONTROLLER:DEBUG: preparing for segue '\(String(describing: segue.identifier))' with id \(self.passId)")
  123. if segue.identifier == "SeguePost"{
  124. (segue.destination as! PostViewController).id = passId
  125. }
  126. if segue.identifier == "SegueAlbum"{
  127. (segue.destination as! AlbumViewController).id = passId
  128. }
  129. if segue.identifier == "SegueSchedule"{
  130. if passId == 1{
  131. (segue.destination as! ScheduleViewController).margolari = true
  132. }
  133. else{
  134. (segue.destination as! ScheduleViewController).margolari = false
  135. }
  136. }
  137. if segue.identifier == "SegueSync"{
  138. self.syncSegue = segue
  139. }
  140. }
  141. override func viewWillAppear(_ animated: Bool) {
  142. NSLog(":CONTROLLER:DEBUG: Forcing a call to populate")
  143. self.populate()
  144. super.viewWillAppear(animated)
  145. }
  146. /**
  147. Run when the app loads.
  148. */
  149. override func viewDidLoad() {
  150. // Ask for location permissions.
  151. locationManager.delegate = self
  152. locationManager.requestWhenInUseAuthorization()
  153. //Hide all sections, except for the first one
  154. self.containerViewLocation.alpha = 0
  155. self.containerViewLablanca.alpha = 0
  156. self.containerViewActivities.alpha = 0
  157. self.containerViewBlog.alpha = 0
  158. self.containerViewGallery.alpha = 0
  159. // Start the location schedule
  160. fetchLocation()
  161. self.locationTimer = Timer.scheduledTimer(timeInterval: 90, target: self, selector: #selector(fetchLocation), userInfo: nil, repeats: true)
  162. //NSLog(":CONTROLLER:DEBUG: Don't skyp sync")
  163. NSLog(":CONTROLLER:DEBUG: Skyp sync")
  164. //Sync()
  165. self.delegate = UIApplication.shared.delegate as? AppDelegate
  166. self.delegate?.controller = self
  167. super.viewDidLoad()
  168. }
  169. func fetchLocation(){
  170. FetchLocation()
  171. }
  172. /**
  173. Actually populates all sections.
  174. As of now, not working.
  175. */
  176. func populate(){
  177. if (self.containerViewHome != nil){
  178. //(self.containerViewHome as HomeView).populate()
  179. //let ng = self.containerViewHome.dbgTxt
  180. //NSLog("AAAAA \(ng)")
  181. }
  182. else{
  183. NSLog("CONTROLLER:ERROR: containerViewHome couldn't be populated: It is nil.")
  184. }
  185. //self.containerLocation.populate()
  186. //self.containerLablanca.populate()
  187. //self.containerViewActivities.populate()
  188. //self.containerViewBlog.populate()
  189. //self.containerGallery.populate()
  190. }
  191. /**
  192. Executed when the view is actually shown.
  193. Performs the initial sync in the first run.
  194. It also generates a user id if none exists.
  195. :param: animated Wether the controller appearance must be animated or not.
  196. */
  197. override func viewDidAppear(_ animated: Bool) {
  198. super.viewDidAppear(animated)
  199. if UserDefaults.standard.object(forKey: "userId") == nil{
  200. let newUid = randomString(length: 16)
  201. let defaults = UserDefaults.standard
  202. defaults.set(newUid, forKey: "userId")
  203. initialSync(showScreen: true)
  204. }
  205. }
  206. /**
  207. Generates a random string to be used as a user identifier.
  208. :param: length The length of the generated string.
  209. :return: A random alphanumeric string with the indicated length.
  210. */
  211. func randomString(length: Int) -> String {
  212. let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  213. let len = UInt32(letters.length)
  214. var randomString = ""
  215. for _ in 0 ..< length {
  216. let rand = arc4random_uniform(len)
  217. var nextChar = letters.character(at: Int(rand))
  218. randomString += NSString(characters: &nextChar, length: 1) as String
  219. }
  220. return randomString
  221. }
  222. /**
  223. Dispose of any resources that can be recreated.
  224. */
  225. override func didReceiveMemoryWarning() {
  226. super.didReceiveMemoryWarning()
  227. }
  228. //Menu items.
  229. let reuseIdentifier = "cell"
  230. var selected = 0
  231. var items = ["Home", "Location", "La Blanca", "Actividades", "Blog", "Gallery"]
  232. // MARK: - UICollectionViewDataSource protocol
  233. /**
  234. Sets a collection of menu items.
  235. :param: numberOfItemsInSection The number of entries of the menu.
  236. :return: The number of entries of the menu.
  237. */
  238. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  239. return self.items.count
  240. }
  241. //Make a cell for each section
  242. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  243. //Get a reference to our storyboard cell
  244. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MenuCollectionViewCell
  245. //Set text
  246. cell.label.text = self.items[indexPath.item]
  247. //Mark the first cell as selected...
  248. if indexPath.item == selected{
  249. cell.bar.backgroundColor = UIColor(red: 90/255, green: 180/255, blue: 255/255, alpha: 1)
  250. cell.label.font = UIFont.boldSystemFont(ofSize: cell.label.font.pointSize)
  251. }
  252. //... and the others as unselected
  253. else{
  254. cell.bar.backgroundColor = UIColor(red: 148/255, green: 209/255, blue: 255/255, alpha: 1)
  255. cell.label.font = UIFont.systemFont(ofSize: cell.label.font.pointSize)
  256. }
  257. return cell
  258. }
  259. // MARK: - UICollectionViewDelegate protocol
  260. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  261. sectionCollection = collectionView
  262. showComponent(selected: indexPath.item)
  263. }
  264. /**
  265. Caled when an item of the menu bar is selected.
  266. :param: selected Index of the selected item.
  267. */
  268. @IBAction func showComponent(selected: Int) {
  269. //Activate label
  270. var i = 0
  271. for cell in sectionCollection.visibleCells as! [MenuCollectionViewCell]{ //TODO: Not only visibles!
  272. if i == selected + 1{
  273. cell.bar.backgroundColor = UIColor(red: 90/255, green: 180/255, blue: 255/255, alpha: 1)
  274. cell.label.font = UIFont.boldSystemFont(ofSize: cell.label.font.pointSize)
  275. }
  276. else{
  277. cell.bar.backgroundColor = UIColor(red: 148/255, green: 209/255, blue: 255/255, alpha: 1)
  278. cell.label.font = UIFont.systemFont(ofSize: cell.label.font.pointSize)
  279. }
  280. i = i + 1
  281. }
  282. //Show the view
  283. if selected == 0 {
  284. UIView.animate(withDuration: 0.5, animations: {
  285. self.containerViewHome.alpha = 1
  286. self.containerViewLocation.alpha = 0
  287. self.containerViewLablanca.alpha = 0
  288. self.containerViewActivities.alpha = 0
  289. self.containerViewBlog.alpha = 0
  290. self.containerViewGallery.alpha = 0
  291. })
  292. }
  293. else if selected == 1 {
  294. UIView.animate(withDuration: 0.5, animations: {
  295. self.containerViewHome.alpha = 0
  296. self.containerViewLocation.alpha = 1
  297. self.containerViewLablanca.alpha = 0
  298. self.containerViewActivities.alpha = 0
  299. self.containerViewBlog.alpha = 0
  300. self.containerViewGallery.alpha = 0
  301. })
  302. }
  303. else if selected == 2 {
  304. UIView.animate(withDuration: 0.5, animations: {
  305. self.containerViewHome.alpha = 0
  306. self.containerViewLocation.alpha = 0
  307. self.containerViewLablanca.alpha = 1
  308. self.containerViewActivities.alpha = 0
  309. self.containerViewBlog.alpha = 0
  310. self.containerViewGallery.alpha = 0
  311. })
  312. }
  313. else if selected == 3 {
  314. UIView.animate(withDuration: 0.5, animations: {
  315. self.containerViewHome.alpha = 0
  316. self.containerViewLocation.alpha = 0
  317. self.containerViewLablanca.alpha = 0
  318. self.containerViewActivities.alpha = 1
  319. self.containerViewBlog.alpha = 0
  320. self.containerViewGallery.alpha = 0
  321. })
  322. }
  323. else if selected == 4 {
  324. UIView.animate(withDuration: 0.5, animations: {
  325. self.containerViewHome.alpha = 0
  326. self.containerViewLocation.alpha = 0
  327. self.containerViewLablanca.alpha = 0
  328. self.containerViewActivities.alpha = 0
  329. self.containerViewBlog.alpha = 1
  330. self.containerViewGallery.alpha = 0
  331. })
  332. }
  333. else if selected == 5 {
  334. UIView.animate(withDuration: 0.5, animations: {
  335. self.containerViewHome.alpha = 0
  336. self.containerViewLocation.alpha = 0
  337. self.containerViewLablanca.alpha = 0
  338. self.containerViewActivities.alpha = 0
  339. self.containerViewBlog.alpha = 0
  340. self.containerViewGallery.alpha = 1
  341. })
  342. }
  343. }
  344. }