ViewController.swift 11 KB

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