ViewController.swift 11 KB

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