HomeView.swift 13 KB

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