GalleryView.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 GalleryView: UIView {
  27. @IBOutlet var container: UIView!
  28. @IBOutlet weak var scrollView: UIScrollView!
  29. @IBOutlet weak var section: Section!
  30. var delegate: AppDelegate? = nil
  31. var idToOpen = -1
  32. // Row list
  33. var rows: Array<RowGallery> = []
  34. override init(frame: CGRect){
  35. super.init(frame: frame)
  36. }
  37. func getRows() -> Array<RowGallery>{
  38. return rows
  39. }
  40. /**
  41. Run when the view is started.
  42. */
  43. required init?(coder aDecoder: NSCoder) {
  44. super.init(coder: aDecoder)
  45. print("GALLERY:DEBUG: init.")
  46. //Load the contents of the HomeView.xib file.
  47. Bundle.main.loadNibNamed("GalleryView", owner: self, options: nil)
  48. self.addSubview(container)
  49. container.frame = self.bounds
  50. section.setTitle(text: "Gallery")
  51. let parent = section.getContentStack()
  52. // Get viewController from StoryBoard
  53. let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
  54. let controller = storyboard.instantiateViewController(withIdentifier: "GMViewController") as! ViewController
  55. // Show albums
  56. let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  57. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  58. self.delegate = appDelegate
  59. let lang : String = getLanguage()
  60. context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
  61. let fetchRequest: NSFetchRequest<Album> = Album.fetchRequest()
  62. let sortDescriptor = NSSortDescriptor(key: "time", ascending: false)
  63. let sortDescriptors = [sortDescriptor]
  64. fetchRequest.sortDescriptors = sortDescriptors
  65. do {
  66. //Get the results
  67. let searchResults = try context.fetch(fetchRequest)
  68. var row : RowGallery
  69. var count = 0
  70. var id: Int
  71. var title: String
  72. for r in searchResults as [NSManagedObject] {
  73. count = count + 1
  74. //Create a new row
  75. row = RowGallery.init(s: "rowGallery\(count)", i: count)
  76. id = r.value(forKey: "id")! as! Int
  77. title = r.value(forKey: "title_\(lang)")! as! String
  78. row.id = id
  79. row.setTitle(text: title)
  80. // Set tap recognizer
  81. //let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(openAlbum(_:)))
  82. //tapRecognizer.delegate = (UIApplication.shared.delegate as! AppDelegate).controller
  83. //row.isUserInteractionEnabled = true
  84. //row.addGestureRecognizer(tapRecognizer)
  85. // Get 4 random images from the album
  86. let imgFetchRequest: NSFetchRequest<Photo_album> = Photo_album.fetchRequest()
  87. // TODO Order random
  88. //let imgSortDescriptor = NSSortDescriptor(key: "time", ascending: true)
  89. //let imgSortDescriptors = [imgSortDescriptor]
  90. //simgFetchRequest.sortDescriptors = imgSortDescriptors
  91. imgFetchRequest.predicate = NSPredicate(format: "album == %i", id)
  92. imgFetchRequest.fetchLimit = 4
  93. do{
  94. let imgSearchResults = try context.fetch(imgFetchRequest)
  95. // Loop images
  96. var imageIdx = 0
  97. for imgR in imgSearchResults as [NSManagedObject]{
  98. let imageId = imgR.value(forKey: "photo")! as! Int
  99. // For each image, I need a new query to fetch from photo entity.
  100. let singleImgFetchRequest: NSFetchRequest<Photo> = Photo.fetchRequest()
  101. singleImgFetchRequest.predicate = NSPredicate(format: "id == %i", imageId)
  102. singleImgFetchRequest.fetchLimit = 4
  103. do{
  104. let singleImgSearchResults = try context.fetch(singleImgFetchRequest)
  105. // Loop image
  106. for sImgR in singleImgSearchResults as [NSManagedObject]{
  107. let image = sImgR.value(forKey: "file")! as! String
  108. row.setImage(idx: imageIdx, filename: image)
  109. }
  110. imageIdx = imageIdx + 1
  111. }
  112. catch {
  113. print("GALLERY:ERROR: Error getting image from photo entity: \(error)")
  114. }
  115. }
  116. } catch {
  117. print("GALLERY:ERROR: Error getting image for post \(id): \(error)")
  118. }
  119. row.backgroundColor = UIColor.red
  120. parent.addArrangedSubview(row)
  121. //row.setNeedsLayout()
  122. //row.layoutIfNeeded()
  123. // Add to the rows array
  124. rows.append(row)
  125. // TODO: Do this on the row didLoad method
  126. // Set tap recognizer
  127. let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(openAlbum(_:)))
  128. row.isUserInteractionEnabled = true
  129. row.addGestureRecognizer(tapRecognizer)
  130. }
  131. } catch {
  132. print("GALLERY:ERROR: Error with request: \(error)")
  133. }
  134. //Always at the end: update scrollview
  135. var h: Int = 0
  136. for view in scrollView.subviews {
  137. //contentRect = contentRect.union(view.frame);
  138. h = h + Int(view.frame.height) + 30 //Why 30?
  139. }
  140. // TODO: Calculate at the end
  141. self.scrollView.contentSize.height = 2500//CGFloat(h);
  142. // The view controller
  143. //var viewController: ViewController = self.window?.rootViewController as! ViewController
  144. //let viewController = UIApplication.topViewController() as! ViewController
  145. //viewController.showPost(id: 4)
  146. //print("BLOG:DEBUG: Show post on load.")
  147. //self.delegate?.controller?.showPost(id: 4)
  148. //controller.showPost(id: 4)
  149. print("GALLERY:DEBUG: Finished loading GalleryView")
  150. //let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(openAlbum(_:)))
  151. //row.isUserInteractionEnabled = true
  152. //container.addGestureRecognizer(tapRecognizer)
  153. self.setUpRowsTapRecognizers()
  154. }
  155. func openAlbum(_ sender:UITapGestureRecognizer? = nil){
  156. print("GALLERY:DEBUG: getting delegate and showing album.")
  157. let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
  158. let id = (sender?.view as! RowGallery).id
  159. delegate.controller?.showAlbum(id: id)
  160. print("GALLERY:DEBUG: Album should be shown.")
  161. }
  162. func getLanguage() -> String{
  163. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  164. if(pre == "es" || pre == "en" || pre == "eu"){
  165. return pre
  166. }
  167. else{
  168. return "es"
  169. }
  170. }
  171. func setUpRowsTapRecognizers(){
  172. print("GALLERY:DEBUG: Setting up tap recognizers")
  173. for row in rows{
  174. let tapRecognizer = UITapGestureRecognizer(target: row, action: #selector(openAlbum(_:)))
  175. row.isUserInteractionEnabled = true
  176. container.addGestureRecognizer(tapRecognizer)
  177. }
  178. }
  179. }