GalleryView.swift 6.0 KB

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