HomeView.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. let location = self.controller.getLocation()
  127. if location != nil {
  128. let d: Int = calculateDistance(lat1: location.latitude, lon1: location.longitude, lat2: lat, lon2: lon)
  129. if d <= 1000 {
  130. self.locationMessage.text = "¡Gasteizko Margolariak está por ahí! A \(d) metros de ti."
  131. }
  132. else{
  133. self.locationMessage.text = "¡Gasteizko Margolariak está por ahí! A \(Int(d/1000)) kilómetros de ti."
  134. }
  135. }
  136. else{
  137. self.locationMessage.text = "¡Gasteizko Margolariak está por ahí!"
  138. }
  139. }
  140. else{
  141. self.locationSection.isHidden = true
  142. }
  143. }
  144. else{
  145. self.locationSection.isHidden = true
  146. }
  147. }
  148. /**
  149. Sets up the La Blanca secction.
  150. Hiddes it if no current festivals.
  151. :param: context App context.
  152. :param: delegate App delegate.
  153. :param: lang Language code (two letter code, lowercase. Only 'es', 'en' and 'eu' supported).
  154. */
  155. func setUpLablanca(context : NSManagedObjectContext, delegate: AppDelegate, lang: String){
  156. // TODO set listener.
  157. let defaults = UserDefaults.standard
  158. if (defaults.value(forKey: "festivals") != nil){
  159. let festivals = defaults.value(forKey: "festivals") as! Int
  160. if festivals == 1{
  161. // TODO: Get current year
  162. let year = 2017
  163. // Get info about festivals
  164. let fetchRequest: NSFetchRequest<Festival> = Festival.fetchRequest()
  165. fetchRequest.predicate = NSPredicate(format: "year = %i", year)
  166. do {
  167. // Get info from festivals
  168. let searchResults = try context.fetch(fetchRequest)
  169. if searchResults.count > 0 {
  170. let r = searchResults[0]
  171. // Set image and text
  172. self.lablancaText.text = (r.value(forKey: "text_\(lang)") as! String?)?.decode().stripHtml()
  173. let filename: String = r.value(forKey: "img") as! String
  174. if (filename == ""){
  175. // Hide the imageview
  176. self.lablancaImage.isHidden = true;
  177. }
  178. else{
  179. let path = "img/blog/thumb/\(filename)"
  180. self.lablancaImage.setImage(localPath: path, remotePath: "https://margolariak.com/\(path)")
  181. }
  182. }
  183. }
  184. catch {
  185. NSLog(":LABLANCA:ERROR: Error getting festivals info: \(error)")
  186. }
  187. }
  188. else{
  189. self.lablancaSection.isHidden = true
  190. }
  191. }
  192. }
  193. /**
  194. Sets up the future activities section.
  195. If none, it hiddes the section.
  196. :param: context App context.
  197. :param: delegate App delegate.
  198. :param: lang Language code (two letter code, lowercase. Only 'es', 'en' and 'eu' supported).
  199. :param: parent Stack view to load the rows in.
  200. */
  201. func setUpFutureActivities(context : NSManagedObjectContext, delegate: AppDelegate, lang: String, parent : UIStackView){
  202. let fetchRequest: NSFetchRequest<Activity> = Activity.fetchRequest()
  203. let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
  204. let sortDescriptors = [sortDescriptor]
  205. fetchRequest.sortDescriptors = sortDescriptors
  206. fetchRequest.predicate = NSPredicate(format: "date > %@", NSDate())
  207. fetchRequest.fetchLimit = 2
  208. do {
  209. let searchResults = try context.fetch(fetchRequest)
  210. var row : RowHomeFutureActivities
  211. var count = 0
  212. var id: Int
  213. var title: String
  214. var text: String
  215. var image: String
  216. if searchResults.count == 0{
  217. self.futureActivitiesSection.isHidden = true
  218. }
  219. else{
  220. for r in searchResults as [NSManagedObject] {
  221. count = count + 1
  222. //Create a new row
  223. row = RowHomeFutureActivities.init(s: "rowHomeFutureActivities\(count)", i: count)
  224. id = r.value(forKey: "id")! as! Int
  225. title = r.value(forKey: "title_\(lang)")! as! String
  226. text = r.value(forKey: "text_\(lang)")! as! String
  227. row.setTitle(text: title)
  228. row.setText(text: text)
  229. row.id = id
  230. // Get main image
  231. image = ""
  232. let imgFetchRequest: NSFetchRequest<Activity_image> = Activity_image.fetchRequest()
  233. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  234. let imgSortDescriptors = [imgSortDescriptor]
  235. imgFetchRequest.sortDescriptors = imgSortDescriptors
  236. imgFetchRequest.predicate = NSPredicate(format: "activity == %i", id)
  237. imgFetchRequest.fetchLimit = 1
  238. do{
  239. let imgSearchResults = try context.fetch(imgFetchRequest)
  240. for imgR in imgSearchResults as [NSManagedObject]{
  241. image = imgR.value(forKey: "image")! as! String
  242. row.setImage(filename: image)
  243. }
  244. }
  245. catch {
  246. NSLog(":HOME:ERROR: Error getting image for activity \(id): \(error)")
  247. }
  248. parent.addArrangedSubview(row)
  249. }
  250. }
  251. }
  252. catch {
  253. NSLog(":HOME:ERROR: Error loading future activities: \(error)")
  254. }
  255. }
  256. /**
  257. Sets up the blog section.
  258. :param: context App context.
  259. :param: delegate App delegate.
  260. :param: lang Language code (two letter code, lowercase. Only 'es', 'en' and 'eu' supported).
  261. :param: parent Stack view to load the rows in.
  262. */
  263. func setUpBlog(context : NSManagedObjectContext, delegate: AppDelegate, lang: String, parent : UIStackView){
  264. let fetchRequest: NSFetchRequest<Post> = Post.fetchRequest()
  265. let sortDescriptor = NSSortDescriptor(key: "dtime", ascending: false)
  266. let sortDescriptors = [sortDescriptor]
  267. fetchRequest.sortDescriptors = sortDescriptors
  268. fetchRequest.fetchLimit = 2
  269. do {
  270. let searchResults = try context.fetch(fetchRequest)
  271. var row : RowHomeBlog
  272. var count = 0
  273. var id: Int
  274. var title: String
  275. var text: String
  276. var image: String
  277. for r in searchResults as [NSManagedObject] {
  278. count = count + 1
  279. //Create a new row
  280. row = RowHomeBlog.init(s: "rowHomeBlog\(count)", i: count)
  281. id = r.value(forKey: "id")! as! Int
  282. title = r.value(forKey: "title_\(lang)")! as! String
  283. text = r.value(forKey: "text_\(lang)")! as! String
  284. row.id = id
  285. row.setTitle(text: title)
  286. row.setText(text: text)
  287. // Get main image
  288. image = ""
  289. let imgFetchRequest: NSFetchRequest<Post_image> = Post_image.fetchRequest()
  290. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  291. let imgSortDescriptors = [imgSortDescriptor]
  292. imgFetchRequest.sortDescriptors = imgSortDescriptors
  293. imgFetchRequest.predicate = NSPredicate(format: "post == %i", id)
  294. imgFetchRequest.fetchLimit = 1
  295. do{
  296. let imgSearchResults = try context.fetch(imgFetchRequest)
  297. for imgR in imgSearchResults as [NSManagedObject]{
  298. image = imgR.value(forKey: "image")! as! String
  299. row.setImage(filename: image)
  300. }
  301. } catch {
  302. NSLog(":HOME:ERROR: Error getting image for post \(id): \(error)")
  303. }
  304. parent.addArrangedSubview(row)
  305. let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(openPost(_:)))
  306. row.isUserInteractionEnabled = true
  307. row.addGestureRecognizer(tapRecognizer)
  308. }
  309. }
  310. catch {
  311. NSLog(":HOME:ERROR: Error loading the blog section: \(error)")
  312. }
  313. }
  314. /**
  315. Sets up the past activities section.
  316. :param: context App context.
  317. :param: delegate App delegate.
  318. :param: lang Language code (two letter code, lowercase. Only 'es', 'en' and 'eu' supported).
  319. :param: parent Stack view to load the rows in.
  320. */
  321. func setUpPastActivities(context : NSManagedObjectContext, delegate: AppDelegate, lang: String, parent : UIStackView){
  322. let fetchRequest: NSFetchRequest<Activity> = Activity.fetchRequest()
  323. let sortDescriptor = NSSortDescriptor(key: "date", ascending: false)
  324. let sortDescriptors = [sortDescriptor]
  325. fetchRequest.sortDescriptors = sortDescriptors
  326. fetchRequest.predicate = NSPredicate(format: "date <= %@", NSDate())
  327. fetchRequest.fetchLimit = 2
  328. do {
  329. let searchResults = try context.fetch(fetchRequest)
  330. var row : RowHomePastActivities
  331. var count = 0
  332. var id: Int
  333. var title: String
  334. var text: String
  335. var image: String
  336. for r in searchResults as [NSManagedObject] {
  337. count = count + 1
  338. //Create a new row
  339. row = RowHomePastActivities.init(s: "rowHomePastActivities\(count)", i: count)
  340. id = r.value(forKey: "id")! as! Int
  341. title = r.value(forKey: "title_\(lang)")! as! String
  342. text = r.value(forKey: "text_\(lang)")! as! String
  343. row.setTitle(text: title)
  344. row.setText(text: text)
  345. row.id = id
  346. // Get main image
  347. image = ""
  348. let imgFetchRequest: NSFetchRequest<Activity_image> = Activity_image.fetchRequest()
  349. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  350. let imgSortDescriptors = [imgSortDescriptor]
  351. imgFetchRequest.sortDescriptors = imgSortDescriptors
  352. imgFetchRequest.predicate = NSPredicate(format: "activity == %i", id)
  353. imgFetchRequest.fetchLimit = 1
  354. do{
  355. let imgSearchResults = try context.fetch(imgFetchRequest)
  356. for imgR in imgSearchResults as [NSManagedObject]{
  357. image = imgR.value(forKey: "image")! as! String
  358. row.setImage(filename: image)
  359. }
  360. }
  361. catch {
  362. NSLog(":HOME:ERROR: Error getting image for past activity \(id): \(error)")
  363. }
  364. parent.addArrangedSubview(row)
  365. }
  366. } catch {
  367. NSLog(":HOME:ERROR: Error loading past activities: \(error)")
  368. }
  369. }
  370. /**
  371. Sets up the future activities section.
  372. :param: context App context.
  373. :param: delegate App delegate.
  374. :param: parent Stack view to load the rows in.
  375. */
  376. func setUpGallery(context : NSManagedObjectContext, delegate: AppDelegate,parent: UIStackView){
  377. // Create the row
  378. var row: RowHomeGallery
  379. row = RowHomeGallery.init(s: "rowHomeGallery", i: 0)
  380. parent.addArrangedSubview(row)
  381. // Set images
  382. let fetchRequest: NSFetchRequest<Photo> = Photo.fetchRequest()
  383. let sortDescriptor = NSSortDescriptor(key: "uploaded", ascending: false)
  384. let sortDescriptors = [sortDescriptor]
  385. fetchRequest.sortDescriptors = sortDescriptors
  386. fetchRequest.fetchLimit = 4
  387. do {
  388. let searchResults = try context.fetch(fetchRequest)
  389. var id: Int
  390. var image: String
  391. var i = 0
  392. for r in searchResults as [NSManagedObject] {
  393. image = r.value(forKey: "file")! as! String
  394. row.setImage(idx: i, filename: image)
  395. NSLog(":HOME:DEBUG: Photo \(i)")
  396. //TODO Set click listener
  397. i = i + 1
  398. }
  399. }
  400. catch{
  401. NSLog(":HOME:ERROR: Error setting gallery up: \(error)")
  402. }
  403. }
  404. /**
  405. Sets up the social section.
  406. :param: parent Stack view to load the rows in.
  407. */
  408. func setUpSocial(parent : UIStackView){
  409. //Create a new row
  410. var row : RowHomeSocial
  411. row = RowHomeSocial.init(s: "rowHomeSocial", i: 0)
  412. parent.addArrangedSubview(row)
  413. }
  414. /**
  415. Converts degrees to radians.
  416. :params: degrees Angle in degrees.
  417. :return: Angle in radians.
  418. */
  419. func degreesToRadians(degrees: Double) -> Double {
  420. return degrees * Double.pi / 180;
  421. }
  422. /**
  423. Calculates the distance between two coordinates.
  424. :param: lat1 Latitude of the first coordinate.
  425. :param: lon1 Longitude of the first coordinate.
  426. :param: lat2 Latitude of the second coordinate.
  427. :param: lon2 Longitude of the second coordinate.
  428. :return: Distance between the points, in meters.
  429. */
  430. func calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double) -> Int {
  431. let eRadius: Double = 6371
  432. let dLat: Double = degreesToRadians(degrees: lat2-lat1)
  433. let dLon: Double = degreesToRadians(degrees: lon2-lon1)
  434. let l1: Double = degreesToRadians(degrees: lat1)
  435. let l2: Double = degreesToRadians(degrees: lat2)
  436. let a: Double = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(l1) * cos(l2)
  437. let c: Double = 2 * atan2(sqrt(a), sqrt(1-a))
  438. let m: Double = eRadius * c * 1000
  439. return Int(m)
  440. }
  441. /**
  442. Opens a post.
  443. */
  444. func openPost(_ sender:UITapGestureRecognizer? = nil){
  445. NSLog(":HOME:DEBUG: Getting delegate and showing post.")
  446. let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
  447. delegate.controller?.showPost(id: (sender?.view as! RowHomeBlog).id)
  448. }
  449. }