HomeView.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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 locationSection: Section!
  31. @IBOutlet weak var lablancaSection: Section!
  32. @IBOutlet weak var futureActivitiesSection: Section!
  33. @IBOutlet weak var blogSection: Section!
  34. @IBOutlet weak var gallerySection: Section!
  35. @IBOutlet weak var pastActivitiesSection: Section!
  36. @IBOutlet weak var socialSection: Section!
  37. var lang: String? = nil
  38. var moc: NSManagedObjectContext? = nil
  39. var appDelegate: AppDelegate? = nil
  40. /**
  41. Run when the view is started.
  42. :param: frame Frame for the view.
  43. */
  44. override init(frame: CGRect){
  45. super.init(frame: frame)
  46. }
  47. /**
  48. Run when the view is started.
  49. :param: coder Application decoder.
  50. */
  51. required init?(coder aDecoder: NSCoder) {
  52. super.init(coder: aDecoder)
  53. // Load the contents of the HomeView.xib file.
  54. Bundle.main.loadNibNamed("HomeView", owner: self, options: nil)
  55. self.addSubview(container)
  56. container.frame = self.bounds
  57. // Set titles for each section
  58. locationSection.setTitle(text: "Encuentranos")
  59. lablancaSection.setTitle(text: "La Blanca")
  60. futureActivitiesSection.setTitle(text: "Proximas actividades")
  61. blogSection.setTitle(text: "Ultimos posts")
  62. gallerySection.setTitle(text: "Ultimas fotos")
  63. pastActivitiesSection.setTitle(text: "Ultimas actividades")
  64. socialSection.setTitle(text: "Siguenos")
  65. // Get info to populate sections
  66. self.moc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  67. self.appDelegate = UIApplication.shared.delegate as! AppDelegate
  68. self.moc?.persistentStoreCoordinator = appDelegate?.persistentStoreCoordinator
  69. self.lang = getLanguage()
  70. // Populate sections
  71. self.populate()
  72. //Always at the end: update scrollview
  73. //var h: Int = 0
  74. //for view in scrollView.subviews {
  75. // //contentRect = contentRect.union(view.frame);
  76. // h = h + Int(view.frame.height) + 30 //Why 30?
  77. // print("curh: \(h)")
  78. //}
  79. // TODO: Calculate at the end
  80. //self.scrollView.contentSize.height = 1300// CGFloat(h);
  81. }
  82. /**
  83. Triggers a reloading (or initial loading) of all sections.
  84. */
  85. func populate(){
  86. NSLog(":HOME:DEBUG: Populating home view.")
  87. //Populate sections
  88. self.setUpPastActivities(context: self.moc!, delegate: appDelegate!, lang: self.lang!, parent: self.pastActivitiesSection.getContentStack())
  89. self.setUpBlog(context: self.moc!, delegate: self.appDelegate!, lang: self.lang!, parent: self.blogSection.getContentStack())
  90. self.setUpFutureActivities(context: self.moc!, delegate: self.appDelegate!, lang: self.lang!, parent: self.futureActivitiesSection.getContentStack())
  91. self.setUpSocial(parent: self.socialSection.getContentStack())
  92. self.setUpGallery(context: self.moc!, delegate: self.appDelegate!, parent: self.gallerySection.getContentStack())
  93. self.pastActivitiesSection.expandSection()
  94. }
  95. /**
  96. Retrieves the device language. The only available ones are Spanish, English and Basque.
  97. :return: Two letter language code (en, eu, es). If other, spanish will be selected.
  98. */
  99. func getLanguage() -> String{
  100. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  101. if(pre == "es" || pre == "en" || pre == "eu"){
  102. return pre
  103. }
  104. else{
  105. return "es"
  106. }
  107. }
  108. /**
  109. Sets the future activities section.
  110. Loads up to two future activities.
  111. :param: context Aplication context.
  112. :param: delegate Application delegate.
  113. :param: lang Device language. Two letter code. Accepts 'es', 'en' and 'eu'.
  114. :param: parent View where the rows will be loaded.
  115. */
  116. func setUpFutureActivities(context : NSManagedObjectContext, delegate: AppDelegate, lang: String, parent : UIStackView){
  117. let fetchRequest: NSFetchRequest<Activity> = Activity.fetchRequest()
  118. let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
  119. let sortDescriptors = [sortDescriptor]
  120. fetchRequest.sortDescriptors = sortDescriptors
  121. fetchRequest.predicate = NSPredicate(format: "date > %@", NSDate())
  122. fetchRequest.fetchLimit = 2
  123. do {
  124. let searchResults = try context.fetch(fetchRequest)
  125. NSLog(":HOME:DEBUG: Future activity count: \(searchResults.count)")
  126. var row : RowHomePastActivities
  127. var count = 0
  128. var id: Int
  129. var title: String
  130. var text: String
  131. var image: String
  132. for r in searchResults as [NSManagedObject] {
  133. count = count + 1
  134. //Create a new row
  135. row = RowHomePastActivities.init(s: "rowHomeFutureActivities\(count)", i: count)
  136. id = r.value(forKey: "id")! as! Int
  137. title = r.value(forKey: "title_\(lang)")! as! String
  138. text = r.value(forKey: "text_\(lang)")! as! String
  139. row.setTitle(text: title)
  140. row.setText(text: text)
  141. // Get main image
  142. image = ""
  143. let imgFetchRequest: NSFetchRequest<Activity_image> = Activity_image.fetchRequest()
  144. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  145. let imgSortDescriptors = [imgSortDescriptor]
  146. imgFetchRequest.sortDescriptors = imgSortDescriptors
  147. imgFetchRequest.predicate = NSPredicate(format: "activity == %i", id)
  148. imgFetchRequest.fetchLimit = 1
  149. do{
  150. let imgSearchResults = try context.fetch(imgFetchRequest)
  151. for imgR in imgSearchResults as [NSManagedObject]{
  152. image = imgR.value(forKey: "image")! as! String
  153. row.setImage(filename: image)
  154. }
  155. } catch {
  156. NSLog(":HOME:ERROR: Error getting image for futureactivity \(id): \(error)")
  157. }
  158. parent.addArrangedSubview(row)
  159. }
  160. } catch {
  161. NSLog(":HOME:ERROR: Error setting the future activities section up: \(error)")
  162. }
  163. }
  164. /**
  165. Sets the blog section.
  166. Loads up to two posts.
  167. :param: context Aplication context.
  168. :param: delegate Application delegate.
  169. :param: lang Device language. Two letter code. Accepts 'es', 'en' and 'eu'.
  170. :param: parent View where the rows will be loaded.
  171. */
  172. func setUpBlog(context : NSManagedObjectContext, delegate: AppDelegate, lang: String, parent : UIStackView){
  173. let fetchRequest: NSFetchRequest<Post> = Post.fetchRequest()
  174. let sortDescriptor = NSSortDescriptor(key: "dtime", ascending: false)
  175. let sortDescriptors = [sortDescriptor]
  176. fetchRequest.sortDescriptors = sortDescriptors
  177. fetchRequest.fetchLimit = 2
  178. do {
  179. let searchResults = try context.fetch(fetchRequest)
  180. NSLog(":HOME:DEBUG: Post count: \(searchResults.count)")
  181. var row : RowHomeBlog
  182. var count = 0
  183. var id: Int
  184. var title: String
  185. var text: String
  186. var image: String
  187. for r in searchResults as [NSManagedObject] {
  188. count = count + 1
  189. //Create a new row
  190. row = RowHomeBlog.init(s: "rowHomeBlog\(count)", i: count)
  191. id = r.value(forKey: "id")! as! Int
  192. title = r.value(forKey: "title_\(lang)")! as! String
  193. text = r.value(forKey: "text_\(lang)")! as! String
  194. row.id = id
  195. row.setTitle(text: title)
  196. row.setText(text: text)
  197. // Get main image
  198. image = ""
  199. let imgFetchRequest: NSFetchRequest<Post_image> = Post_image.fetchRequest()
  200. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  201. let imgSortDescriptors = [imgSortDescriptor]
  202. imgFetchRequest.sortDescriptors = imgSortDescriptors
  203. imgFetchRequest.predicate = NSPredicate(format: "post == %i", id)
  204. imgFetchRequest.fetchLimit = 1
  205. do{
  206. let imgSearchResults = try context.fetch(imgFetchRequest)
  207. for imgR in imgSearchResults as [NSManagedObject]{
  208. image = imgR.value(forKey: "image")! as! String
  209. row.setImage(filename: image)
  210. }
  211. } catch {
  212. NSLog(":HOME:ERROR: Error getting image for post \(id): \(error)")
  213. }
  214. parent.addArrangedSubview(row)
  215. let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(openPost(_:)))
  216. row.isUserInteractionEnabled = true
  217. row.addGestureRecognizer(tapRecognizer)
  218. }
  219. } catch {
  220. NSLog(":HOME:ERROR: Error setting the blog section up: \(error)")
  221. }
  222. }
  223. /**
  224. Sets the past activities section.
  225. Loads up to two past activities.
  226. :param: context Aplication context.
  227. :param: delegate Application delegate.
  228. :param: lang Device language. Two letter code. Accepts 'es', 'en' and 'eu'.
  229. :param: parent View where the rows will be loaded.
  230. */
  231. func setUpPastActivities(context : NSManagedObjectContext, delegate: AppDelegate, lang: String, parent : UIStackView){
  232. let fetchRequest: NSFetchRequest<Activity> = Activity.fetchRequest()
  233. let sortDescriptor = NSSortDescriptor(key: "date", ascending: false)
  234. let sortDescriptors = [sortDescriptor]
  235. fetchRequest.sortDescriptors = sortDescriptors
  236. fetchRequest.predicate = NSPredicate(format: "date <= %@", NSDate())
  237. fetchRequest.fetchLimit = 2
  238. do {
  239. let searchResults = try context.fetch(fetchRequest)
  240. NSLog(":HOME:LOG: Setting past activities up. Count: \(searchResults.count)")
  241. var row : RowHomePastActivities
  242. var count = 0
  243. var id: Int
  244. var title: String
  245. var text: String
  246. var image: String
  247. for r in searchResults as [NSManagedObject] {
  248. count = count + 1
  249. //Create a new row
  250. row = RowHomePastActivities.init(s: "rowHomePastActivities\(count)", i: count)
  251. id = r.value(forKey: "id")! as! Int
  252. title = r.value(forKey: "title_\(lang)")! as! String
  253. text = r.value(forKey: "text_\(lang)")! as! String
  254. row.setTitle(text: title)
  255. row.setText(text: text)
  256. // Get main image
  257. image = ""
  258. let imgFetchRequest: NSFetchRequest<Activity_image> = Activity_image.fetchRequest()
  259. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  260. let imgSortDescriptors = [imgSortDescriptor]
  261. imgFetchRequest.sortDescriptors = imgSortDescriptors
  262. imgFetchRequest.predicate = NSPredicate(format: "activity == %i", id)
  263. imgFetchRequest.fetchLimit = 1
  264. do{
  265. let imgSearchResults = try context.fetch(imgFetchRequest)
  266. for imgR in imgSearchResults as [NSManagedObject]{
  267. image = imgR.value(forKey: "image")! as! String
  268. row.setImage(filename: image)
  269. }
  270. } catch {
  271. NSLog(":HOME:ERROR: Error getting image for past activity \(id): \(error)")
  272. }
  273. parent.addArrangedSubview(row)
  274. }
  275. } catch {
  276. NSLog(":HOME:ERROR: Error setting the past activities section up: \(error)")
  277. }
  278. }
  279. /**
  280. Sets the fgallery section.
  281. Loads up to four photos.
  282. :param: context Aplication context.
  283. :param: delegate Application delegate.
  284. :param: parent View where the rows will be loaded.
  285. */
  286. func setUpGallery(context : NSManagedObjectContext, delegate: AppDelegate,parent: UIStackView){
  287. NSLog(":HOME:LOG: Setting gallery section up.")
  288. // Create the row
  289. var row: RowHomeGallery
  290. row = RowHomeGallery.init(s: "rowHomeGallery", i: 0)
  291. parent.addArrangedSubview(row)
  292. // Set images
  293. let fetchRequest: NSFetchRequest<Photo> = Photo.fetchRequest()
  294. let sortDescriptor = NSSortDescriptor(key: "uploaded", ascending: false)
  295. let sortDescriptors = [sortDescriptor]
  296. fetchRequest.sortDescriptors = sortDescriptors
  297. fetchRequest.fetchLimit = 4
  298. do {
  299. let searchResults = try context.fetch(fetchRequest)
  300. var image: String
  301. // Loop images
  302. var i = 0
  303. for r in searchResults as [NSManagedObject] {
  304. image = r.value(forKey: "file")! as! String
  305. row.setImage(idx: i, filename: image)
  306. //TODO Set click listener
  307. i = i + 1
  308. }
  309. }
  310. catch{
  311. NSLog(":HOME:ERROR: Error setting gallery up: \(error)")
  312. }
  313. }
  314. /**
  315. Sets the social section.
  316. :param: parent View where the rows will be loaded.
  317. */
  318. func setUpSocial(parent : UIStackView){
  319. NSLog(":HOME:LOG: Setting soceial section up.")
  320. //Create a new row
  321. var row : RowHomeSocial
  322. row = RowHomeSocial.init(s: "rowHomeSocial", i: 0)
  323. parent.addArrangedSubview(row)
  324. }
  325. /**
  326. opens the blog section, showing a post.
  327. :param: sender: View calling the function.
  328. */
  329. func openPost(_ sender:UITapGestureRecognizer? = nil){
  330. NSLog(":HOME:DEBUG: Getting delegate and showing post.")
  331. let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
  332. delegate.controller?.showPost(id: (sender?.view as! RowHomeBlog).id)
  333. NSLog(":HOME:DEBUG: Post should be shown.")
  334. }
  335. }