HomeView.swift 18 KB

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