ViewController.swift 11 KB

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