HomeView.swift 13 KB

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