HomeView.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. :param: coder Coder.
  59. */
  60. required init?(coder aDecoder: NSCoder) {
  61. self.storyboard = UIStoryboard(name: "Main", bundle: nil)
  62. self.controller = storyboard.instantiateViewController(withIdentifier: "GMViewController") as! ViewController
  63. super.init(coder: aDecoder)
  64. //Load the contents of the HomeView.xib file.
  65. Bundle.main.loadNibNamed("HomeView", owner: self, options: nil)
  66. self.addSubview(container)
  67. container.frame = self.bounds
  68. //Set titles for each section
  69. futureActivitiesSection.setTitle(text: "Próximas actividades")
  70. blogSection.setTitle(text: "Últimos posts")
  71. gallerySection.setTitle(text: "Últimas fotos")
  72. pastActivitiesSection.setTitle(text: "Últimas actividades")
  73. socialSection.setTitle(text: "Síguenos")
  74. //Get info to populate sections
  75. self.moc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  76. self.delegate = UIApplication.shared.delegate as! AppDelegate
  77. self.moc?.persistentStoreCoordinator = self.delegate?.persistentStoreCoordinator
  78. self.lang = getLanguage()
  79. // Populate section.
  80. populate()
  81. // Special case: Location
  82. // Set up once and start and periodically witha timer.
  83. setUpLocation()
  84. Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(setUpLocation), userInfo: nil, repeats: true)
  85. }
  86. /**
  87. Sets all the sections up
  88. */
  89. func populate(){
  90. //Populate sections
  91. setUpPastActivities(context: self.moc!, delegate: self.delegate!, lang: self.lang!, parent: self.pastActivitiesSection.getContentStack())
  92. setUpBlog(context: self.moc!, delegate: self.delegate!, lang: self.lang!, parent: self.blogSection.getContentStack())
  93. setUpFutureActivities(context: self.moc!, delegate: self.delegate!, lang: self.lang!, parent: self.futureActivitiesSection.getContentStack())
  94. setUpSocial(parent: self.socialSection.getContentStack())
  95. setUpGallery(context: self.moc!, delegate: self.delegate!, parent: self.gallerySection.getContentStack())
  96. setUpLablanca(context: self.moc!, delegate: self.delegate!, lang: self.lang!)
  97. }
  98. /**
  99. Gets the device language. The only recognized languages are Spanish, English and Basque.
  100. If the device has another language, Spanish will be selected by default.
  101. :return: Two-letter language code.
  102. */
  103. func getLanguage() -> String{
  104. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  105. if(pre == "es" || pre == "en" || pre == "eu"){
  106. return pre
  107. }
  108. else{
  109. return "es"
  110. }
  111. }
  112. /**
  113. Sets up the location section.
  114. If no location is reported, it hiddes the section.
  115. */
  116. func setUpLocation(){
  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/fiestas/thumb/\(filename)"
  187. self.lablancaImage.setImage(localPath: path, remotePath: "https://margolariak.com/\(path)")
  188. }
  189. }
  190. }
  191. catch {
  192. NSLog(":HOME:ERROR: Error getting setting the La Blanca section up: \(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. }
  374. catch {
  375. NSLog(":HOME:ERROR: Error loading past activities: \(error)")
  376. }
  377. }
  378. /**
  379. Sets up the future activities section.
  380. :param: context App context.
  381. :param: delegate App delegate.
  382. :param: parent Stack view to load the rows in.
  383. */
  384. func setUpGallery(context : NSManagedObjectContext, delegate: AppDelegate,parent: UIStackView){
  385. // Create the row
  386. var row: RowHomeGallery
  387. row = RowHomeGallery.init(s: "rowHomeGallery", i: 0)
  388. parent.addArrangedSubview(row)
  389. // Set images
  390. let fetchRequest: NSFetchRequest<Photo> = Photo.fetchRequest()
  391. let sortDescriptor = NSSortDescriptor(key: "uploaded", ascending: false)
  392. let sortDescriptors = [sortDescriptor]
  393. fetchRequest.sortDescriptors = sortDescriptors
  394. fetchRequest.fetchLimit = 4
  395. do {
  396. let searchResults = try context.fetch(fetchRequest)
  397. var id: Int
  398. var image: String
  399. var albumId: Int
  400. var i = 0
  401. for r in searchResults as [NSManagedObject] {
  402. image = r.value(forKey: "file")! as! String
  403. id = r.value(forKey: "id")! as! Int
  404. // TODO Get album id
  405. // Get album title
  406. let albumFetchRequest: NSFetchRequest<Photo_album> = Photo_album.fetchRequest()
  407. albumFetchRequest.predicate = NSPredicate(format: "photo = %i", id)
  408. do {
  409. let results = try context.fetch(albumFetchRequest)
  410. let r = results[0]
  411. albumId = r.value(forKey: "album")! as! Int
  412. row.albumIds[i] = albumId
  413. }
  414. catch {
  415. NSLog(":GALLERYCONTROLLER:ERROR: Error getting album info: \(error)")
  416. }
  417. row.setImage(idx: i, filename: image)
  418. row.photoIds[i] = id
  419. i = i + 1
  420. }
  421. }
  422. catch{
  423. NSLog(":HOME:ERROR: Error setting gallery up: \(error)")
  424. }
  425. }
  426. /**
  427. Sets up the social section.
  428. :param: parent Stack view to load the rows in.
  429. */
  430. func setUpSocial(parent : UIStackView){
  431. //Create a new row
  432. var row : RowHomeSocial
  433. row = RowHomeSocial.init(s: "rowHomeSocial", i: 0)
  434. parent.addArrangedSubview(row)
  435. }
  436. /**
  437. Converts degrees to radians.
  438. :params: degrees Angle in degrees.
  439. :return: Angle in radians.
  440. */
  441. func degreesToRadians(degrees: Double) -> Double {
  442. return degrees * Double.pi / 180;
  443. }
  444. /**
  445. Calculates the distance between two coordinates.
  446. :param: lat1 Latitude of the first coordinate.
  447. :param: lon1 Longitude of the first coordinate.
  448. :param: lat2 Latitude of the second coordinate.
  449. :param: lon2 Longitude of the second coordinate.
  450. :return: Distance between the points, in meters.
  451. */
  452. func calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double) -> Int {
  453. let eRadius: Double = 6371
  454. let dLat: Double = degreesToRadians(degrees: lat2-lat1)
  455. let dLon: Double = degreesToRadians(degrees: lon2-lon1)
  456. let l1: Double = degreesToRadians(degrees: lat1)
  457. let l2: Double = degreesToRadians(degrees: lat2)
  458. let a: Double = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(l1) * cos(l2)
  459. let c: Double = 2 * atan2(sqrt(a), sqrt(1-a))
  460. let m: Double = eRadius * c * 1000
  461. return Int(m)
  462. }
  463. /**
  464. Opens a post.
  465. */
  466. func openPost(_ sender:UITapGestureRecognizer? = nil){
  467. let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
  468. delegate.controller?.showPost(id: (sender?.view as! RowHomeBlog).id)
  469. }
  470. /**
  471. Opens the La Blanca section when tapping the section.
  472. */
  473. func openLablanca(_ sender:UITapGestureRecognizer? = nil){
  474. let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
  475. delegate.controller?.showComponent(selected: 2)
  476. }
  477. /**
  478. Opens the Location section when tapping the section.
  479. */
  480. func openLocation(_ sender:UITapGestureRecognizer? = nil){
  481. let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
  482. delegate.controller?.showComponent(selected: 1)
  483. }
  484. }