HomeView.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 Foundation
  21. import CoreData
  22. import UIKit
  23. /**
  24. Class to handle the home view.
  25. */
  26. class HomeView: UIView {
  27. // Outlets
  28. @IBOutlet weak var scrollView: UIScrollView!
  29. @IBOutlet weak var container: UIView!
  30. @IBOutlet weak var locationMessage: UILabel!
  31. //Each of the sections of the view.
  32. @IBOutlet weak var locationSection: UIView!
  33. @IBOutlet weak var lablancaSection: Section!
  34. @IBOutlet weak var futureActivitiesSection: Section!
  35. @IBOutlet weak var blogSection: Section!
  36. @IBOutlet weak var gallerySection: Section!
  37. @IBOutlet weak var pastActivitiesSection: Section!
  38. @IBOutlet weak var socialSection: Section!
  39. var moc: NSManagedObjectContext? = nil
  40. var delegate: AppDelegate? = nil
  41. var lang: String? = nil
  42. var locationTimer: Timer? = nil
  43. var controller: ViewController
  44. var storyboard: UIStoryboard
  45. /**
  46. Default constructor for the storyboard.
  47. :param: frame View frame.
  48. */
  49. override init(frame: CGRect){
  50. self.storyboard = UIStoryboard(name: "Main", bundle: nil)
  51. self.controller = storyboard.instantiateViewController(withIdentifier: "GMViewController") as! ViewController
  52. super.init(frame: frame)
  53. }
  54. /**
  55. Run when the view is started.
  56. */
  57. required init?(coder aDecoder: NSCoder) {
  58. self.storyboard = UIStoryboard(name: "Main", bundle: nil)
  59. self.controller = storyboard.instantiateViewController(withIdentifier: "GMViewController") as! ViewController
  60. super.init(coder: aDecoder)
  61. //Load the contents of the HomeView.xib file.
  62. Bundle.main.loadNibNamed("HomeView", owner: self, options: nil)
  63. self.addSubview(container)
  64. container.frame = self.bounds
  65. //Set titles for each section
  66. lablancaSection.setTitle(text: "La Blanca")
  67. futureActivitiesSection.setTitle(text: "Próximas actividades")
  68. blogSection.setTitle(text: "Últimos posts")
  69. gallerySection.setTitle(text: "Últimas fotos")
  70. pastActivitiesSection.setTitle(text: "Últimas actividades")
  71. socialSection.setTitle(text: "Síguenos")
  72. //Get info to populate sections
  73. self.moc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  74. self.delegate = UIApplication.shared.delegate as! AppDelegate
  75. self.moc?.persistentStoreCoordinator = self.delegate?.persistentStoreCoordinator
  76. self.lang = getLanguage()
  77. // Populate section.
  78. populate()
  79. // Special case: Location
  80. // Set up once and start and periodically witha timer.
  81. setUpLocation()
  82. Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(setUpLocation), userInfo: nil, repeats: true)
  83. }
  84. /**
  85. Sets all the sections up
  86. */
  87. func populate(){
  88. //Populate sections
  89. setUpPastActivities(context: self.moc!, delegate: self.delegate!, lang: self.lang!, parent: self.pastActivitiesSection.getContentStack())
  90. setUpBlog(context: self.moc!, delegate: self.delegate!, lang: self.lang!, parent: self.blogSection.getContentStack())
  91. setUpFutureActivities(context: self.moc!, delegate: self.delegate!, lang: self.lang!, parent: self.futureActivitiesSection.getContentStack())
  92. setUpSocial(parent: self.socialSection.getContentStack())
  93. setUpGallery(context: self.moc!, delegate: self.delegate!, parent: self.gallerySection.getContentStack())
  94. setUpLablanca(context: self.moc!, delegate: self.delegate!, lang: self.lang!)
  95. }
  96. /**
  97. Gets the device language. The only recognized languages are Spanish, English and Basque.
  98. If the device has another language, Spanish will be selected by default.
  99. :return: Two-letter language code.
  100. */
  101. func getLanguage() -> String{
  102. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  103. if(pre == "es" || pre == "en" || pre == "eu"){
  104. return pre
  105. }
  106. else{
  107. return "es"
  108. }
  109. }
  110. /**
  111. Sets up the location section.
  112. If no location is reported, it hiddes the section.
  113. */
  114. func setUpLocation(){
  115. // TODO: Also set up tap recognizer.
  116. let defaults = UserDefaults.standard
  117. if (defaults.value(forKey: "GMLocLat") != nil && defaults.value(forKey: "GMLocLon") != nil){
  118. let lat = defaults.value(forKey: "GMLocLat") as! Double
  119. let lon = defaults.value(forKey: "GMLocLon") as! Double
  120. let time = defaults.value(forKey: "GMLocTime") as! Date
  121. let cTime = Date()
  122. let minutes = Calendar.current.dateComponents([.minute], from: time, to: cTime).minute
  123. if (minutes! < 30){
  124. self.locationSection.isHidden = false
  125. let location = self.controller.getLocation()
  126. if location != nil {
  127. let d: Int = calculateDistance(lat1: location.latitude, lon1: location.longitude, lat2: lat, lon2: lon)
  128. if d <= 1000 {
  129. self.locationMessage.text = "¡Gasteizko Margolariak está por ahí! A \(d) metros de ti."
  130. }
  131. else{
  132. self.locationMessage.text = "¡Gasteizko Margolariak está por ahí! A \(Int(d/1000)) kilómetros de ti."
  133. }
  134. }
  135. else{
  136. self.locationMessage.text = "¡Gasteizko Margolariak está por ahí!"
  137. }
  138. }
  139. else{
  140. self.locationSection.isHidden = true
  141. }
  142. }
  143. else{
  144. self.locationSection.isHidden = true
  145. }
  146. }
  147. /**
  148. Sets up the La Blanca secction.
  149. Hiddes it if no current festivals.
  150. :param: context App context.
  151. :param: delegate App delegate.
  152. :param: lang Language code (two letter code, lowercase. Only 'es', 'en' and 'eu' supported).
  153. */
  154. func setUpLablanca(context : NSManagedObjectContext, delegate: AppDelegate, lang: String){
  155. let defaults = UserDefaults.standard
  156. if (defaults.value(forKey: "festivals") != nil){
  157. let festivals = defaults.value(forKey: "festivals") as! Int
  158. if festivals == 1{
  159. // TODO Actualy show something
  160. }
  161. else{
  162. self.lablancaSection.isHidden = true
  163. }
  164. }
  165. }
  166. /**
  167. Sets up the future activities section.
  168. If none, it hiddes the section.
  169. :param: context App context.
  170. :param: delegate App delegate.
  171. :param: lang Language code (two letter code, lowercase. Only 'es', 'en' and 'eu' supported).
  172. :param: parent Stack view to load the rows in.
  173. */
  174. func setUpFutureActivities(context : NSManagedObjectContext, delegate: AppDelegate, lang: String, parent : UIStackView){
  175. let fetchRequest: NSFetchRequest<Activity> = Activity.fetchRequest()
  176. let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
  177. let sortDescriptors = [sortDescriptor]
  178. fetchRequest.sortDescriptors = sortDescriptors
  179. fetchRequest.predicate = NSPredicate(format: "date > %@", NSDate())
  180. fetchRequest.fetchLimit = 2
  181. do {
  182. let searchResults = try context.fetch(fetchRequest)
  183. var row : RowHomeFutureActivities
  184. var count = 0
  185. var id: Int
  186. var title: String
  187. var text: String
  188. var image: String
  189. if searchResults.count == 0{
  190. self.futureActivitiesSection.isHidden = true
  191. }
  192. else{
  193. for r in searchResults as [NSManagedObject] {
  194. count = count + 1
  195. //Create a new row
  196. row = RowHomeFutureActivities.init(s: "rowHomeFutureActivities\(count)", i: count)
  197. id = r.value(forKey: "id")! as! Int
  198. title = r.value(forKey: "title_\(lang)")! as! String
  199. text = r.value(forKey: "text_\(lang)")! as! String
  200. row.setTitle(text: title)
  201. row.setText(text: text)
  202. row.id = id
  203. // Get main image
  204. image = ""
  205. let imgFetchRequest: NSFetchRequest<Activity_image> = Activity_image.fetchRequest()
  206. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  207. let imgSortDescriptors = [imgSortDescriptor]
  208. imgFetchRequest.sortDescriptors = imgSortDescriptors
  209. imgFetchRequest.predicate = NSPredicate(format: "activity == %i", id)
  210. imgFetchRequest.fetchLimit = 1
  211. do{
  212. let imgSearchResults = try context.fetch(imgFetchRequest)
  213. for imgR in imgSearchResults as [NSManagedObject]{
  214. image = imgR.value(forKey: "image")! as! String
  215. row.setImage(filename: image)
  216. }
  217. }
  218. catch {
  219. NSLog(":HOME:ERROR: Error getting image for activity \(id): \(error)")
  220. }
  221. parent.addArrangedSubview(row)
  222. }
  223. }
  224. }
  225. catch {
  226. NSLog(":HOME:ERROR: Error loading future activities: \(error)")
  227. }
  228. }
  229. /**
  230. Sets up the blog section.
  231. :param: context App context.
  232. :param: delegate App delegate.
  233. :param: lang Language code (two letter code, lowercase. Only 'es', 'en' and 'eu' supported).
  234. :param: parent Stack view to load the rows in.
  235. */
  236. func setUpBlog(context : NSManagedObjectContext, delegate: AppDelegate, lang: String, parent : UIStackView){
  237. let fetchRequest: NSFetchRequest<Post> = Post.fetchRequest()
  238. let sortDescriptor = NSSortDescriptor(key: "dtime", ascending: false)
  239. let sortDescriptors = [sortDescriptor]
  240. fetchRequest.sortDescriptors = sortDescriptors
  241. fetchRequest.fetchLimit = 2
  242. do {
  243. let searchResults = try context.fetch(fetchRequest)
  244. var row : RowHomeBlog
  245. var count = 0
  246. var id: Int
  247. var title: String
  248. var text: String
  249. var image: String
  250. for r in searchResults as [NSManagedObject] {
  251. count = count + 1
  252. //Create a new row
  253. row = RowHomeBlog.init(s: "rowHomeBlog\(count)", i: count)
  254. id = r.value(forKey: "id")! as! Int
  255. title = r.value(forKey: "title_\(lang)")! as! String
  256. text = r.value(forKey: "text_\(lang)")! as! String
  257. row.id = id
  258. row.setTitle(text: title)
  259. row.setText(text: text)
  260. // Get main image
  261. image = ""
  262. let imgFetchRequest: NSFetchRequest<Post_image> = Post_image.fetchRequest()
  263. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  264. let imgSortDescriptors = [imgSortDescriptor]
  265. imgFetchRequest.sortDescriptors = imgSortDescriptors
  266. imgFetchRequest.predicate = NSPredicate(format: "post == %i", id)
  267. imgFetchRequest.fetchLimit = 1
  268. do{
  269. let imgSearchResults = try context.fetch(imgFetchRequest)
  270. for imgR in imgSearchResults as [NSManagedObject]{
  271. image = imgR.value(forKey: "image")! as! String
  272. row.setImage(filename: image)
  273. }
  274. } catch {
  275. NSLog(":HOME:ERROR: Error getting image for post \(id): \(error)")
  276. }
  277. parent.addArrangedSubview(row)
  278. let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(openPost(_:)))
  279. row.isUserInteractionEnabled = true
  280. row.addGestureRecognizer(tapRecognizer)
  281. }
  282. }
  283. catch {
  284. NSLog(":HOME:ERROR: Error loading the blog section: \(error)")
  285. }
  286. }
  287. /**
  288. Sets up the past activities section.
  289. :param: context App context.
  290. :param: delegate App delegate.
  291. :param: lang Language code (two letter code, lowercase. Only 'es', 'en' and 'eu' supported).
  292. :param: parent Stack view to load the rows in.
  293. */
  294. func setUpPastActivities(context : NSManagedObjectContext, delegate: AppDelegate, lang: String, parent : UIStackView){
  295. let fetchRequest: NSFetchRequest<Activity> = Activity.fetchRequest()
  296. let sortDescriptor = NSSortDescriptor(key: "date", ascending: false)
  297. let sortDescriptors = [sortDescriptor]
  298. fetchRequest.sortDescriptors = sortDescriptors
  299. fetchRequest.predicate = NSPredicate(format: "date <= %@", NSDate())
  300. fetchRequest.fetchLimit = 2
  301. do {
  302. let searchResults = try context.fetch(fetchRequest)
  303. var row : RowHomePastActivities
  304. var count = 0
  305. var id: Int
  306. var title: String
  307. var text: String
  308. var image: String
  309. for r in searchResults as [NSManagedObject] {
  310. count = count + 1
  311. //Create a new row
  312. row = RowHomePastActivities.init(s: "rowHomePastActivities\(count)", i: count)
  313. id = r.value(forKey: "id")! as! Int
  314. title = r.value(forKey: "title_\(lang)")! as! String
  315. text = r.value(forKey: "text_\(lang)")! as! String
  316. row.setTitle(text: title)
  317. row.setText(text: text)
  318. row.id = id
  319. // Get main image
  320. image = ""
  321. let imgFetchRequest: NSFetchRequest<Activity_image> = Activity_image.fetchRequest()
  322. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  323. let imgSortDescriptors = [imgSortDescriptor]
  324. imgFetchRequest.sortDescriptors = imgSortDescriptors
  325. imgFetchRequest.predicate = NSPredicate(format: "activity == %i", id)
  326. imgFetchRequest.fetchLimit = 1
  327. do{
  328. let imgSearchResults = try context.fetch(imgFetchRequest)
  329. for imgR in imgSearchResults as [NSManagedObject]{
  330. image = imgR.value(forKey: "image")! as! String
  331. row.setImage(filename: image)
  332. }
  333. }
  334. catch {
  335. NSLog(":HOME:ERROR: Error getting image for past activity \(id): \(error)")
  336. }
  337. parent.addArrangedSubview(row)
  338. }
  339. } catch {
  340. NSLog(":HOME:ERROR: Error loading past activities: \(error)")
  341. }
  342. }
  343. /**
  344. Sets up the future activities section.
  345. :param: context App context.
  346. :param: delegate App delegate.
  347. :param: parent Stack view to load the rows in.
  348. */
  349. func setUpGallery(context : NSManagedObjectContext, delegate: AppDelegate,parent: UIStackView){
  350. // Create the row
  351. var row: RowHomeGallery
  352. row = RowHomeGallery.init(s: "rowHomeGallery", i: 0)
  353. parent.addArrangedSubview(row)
  354. // Set images
  355. let fetchRequest: NSFetchRequest<Photo> = Photo.fetchRequest()
  356. let sortDescriptor = NSSortDescriptor(key: "uploaded", ascending: false)
  357. let sortDescriptors = [sortDescriptor]
  358. fetchRequest.sortDescriptors = sortDescriptors
  359. fetchRequest.fetchLimit = 4
  360. do {
  361. let searchResults = try context.fetch(fetchRequest)
  362. var id: Int
  363. var image: String
  364. var i = 0
  365. for r in searchResults as [NSManagedObject] {
  366. image = r.value(forKey: "file")! as! String
  367. row.setImage(idx: i, filename: image)
  368. NSLog(":HOME:DEBUG: Photo \(i)")
  369. //TODO Set click listener
  370. i = i + 1
  371. }
  372. }
  373. catch{
  374. NSLog(":HOME:ERROR: Error setting gallery up: \(error)")
  375. }
  376. }
  377. /**
  378. Sets up the social section.
  379. :param: parent Stack view to load the rows in.
  380. */
  381. func setUpSocial(parent : UIStackView){
  382. //Create a new row
  383. var row : RowHomeSocial
  384. row = RowHomeSocial.init(s: "rowHomeSocial", i: 0)
  385. parent.addArrangedSubview(row)
  386. }
  387. /**
  388. Converts degrees to radians.
  389. :params: degrees Angle in degrees.
  390. :return: Angle in radians.
  391. */
  392. func degreesToRadians(degrees: Double) -> Double {
  393. return degrees * Double.pi / 180;
  394. }
  395. /**
  396. Calculates the distance between two coordinates.
  397. :param: lat1 Latitude of the first coordinate.
  398. :param: lon1 Longitude of the first coordinate.
  399. :param: lat2 Latitude of the second coordinate.
  400. :param: lon2 Longitude of the second coordinate.
  401. :return: Distance between the points, in meters.
  402. */
  403. func calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double) -> Int {
  404. let eRadius: Double = 6371
  405. let dLat: Double = degreesToRadians(degrees: lat2-lat1)
  406. let dLon: Double = degreesToRadians(degrees: lon2-lon1)
  407. let l1: Double = degreesToRadians(degrees: lat1)
  408. let l2: Double = degreesToRadians(degrees: lat2)
  409. let a: Double = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(l1) * cos(l2)
  410. let c: Double = 2 * atan2(sqrt(a), sqrt(1-a))
  411. let m: Double = eRadius * c * 1000
  412. return Int(m)
  413. }
  414. /**
  415. Opens a post.
  416. */
  417. func openPost(_ sender:UITapGestureRecognizer? = nil){
  418. NSLog(":HOME:DEBUG: Getting delegate and showing post.")
  419. let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
  420. delegate.controller?.showPost(id: (sender?.view as! RowHomeBlog).id)
  421. }
  422. }