PhotoViewController.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 UIKit
  21. import CoreData
  22. /**
  23. The view controller of the app.
  24. */
  25. class PhotoViewController: UIViewController, UIGestureRecognizerDelegate {
  26. @IBOutlet weak var barButton: UIButton!
  27. @IBOutlet weak var barTitle: UILabel!
  28. @IBOutlet weak var photoTitle: UILabel!
  29. @IBOutlet weak var photoImage: UIImageView!
  30. @IBOutlet weak var photoDate: UILabel!
  31. @IBOutlet weak var btPrev: UIButton!
  32. @IBOutlet weak var btNext: UIButton!
  33. var albumId: Int = -1
  34. var photoId: Int = -1
  35. var photoIds: [Int] = []
  36. var photoIdx: Int = 0
  37. var passPhotoId: Int = -1
  38. var passAlbumId: Int = -1
  39. var albumTitle: String = ""
  40. var delegate: AppDelegate?
  41. /**
  42. Gets the application context.
  43. :return: The application context.
  44. */
  45. func getContext () -> NSManagedObjectContext {
  46. return NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
  47. }
  48. /**
  49. Run when the app loads.
  50. */
  51. override func viewDidLoad() {
  52. NSLog(":PHOTO:DEBUG: viewDidLoad")
  53. // Populate photo array.
  54. let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  55. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  56. let lang : String = getLanguage()
  57. context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
  58. let fetchRequest: NSFetchRequest<Photo_album> = Photo_album.fetchRequest()
  59. fetchRequest.predicate = NSPredicate(format: "album = %i", albumId)
  60. do {
  61. let searchResults = try context.fetch(fetchRequest)
  62. var id: Int
  63. var i = 0
  64. for r in searchResults as [NSManagedObject] {
  65. id = r.value(forKey: "photo")! as! Int
  66. photoIds.append(id)
  67. if id == photoId{
  68. photoIdx = i
  69. }
  70. i = i + 1
  71. }
  72. // Get album title
  73. let albumFetchRequest: NSFetchRequest<Album> = Album.fetchRequest()
  74. albumFetchRequest.predicate = NSPredicate(format: "id = %i", albumId)
  75. do {
  76. let results = try context.fetch(albumFetchRequest)
  77. let r = results[0]
  78. self.albumTitle = r.value(forKey: "title_\(lang)")! as! String
  79. }
  80. catch {
  81. NSLog(":GALLERYCONTROLLER:ERROR: Error getting album info: \(error)")
  82. }
  83. } catch {
  84. NSLog(":PHOTO:ERROR: Error getting infor from album \(albumId): \(error)")
  85. }
  86. // Set up buttons
  87. let tapRecognizerNext = UITapGestureRecognizer(target: self, action: #selector(nextPhoto(_:)))
  88. btNext.isUserInteractionEnabled = true
  89. btNext.addGestureRecognizer(tapRecognizerNext)
  90. let tapRecognizerPrev = UITapGestureRecognizer(target: self, action: #selector(prevPhoto(_:)))
  91. btPrev.isUserInteractionEnabled = true
  92. btPrev.addGestureRecognizer(tapRecognizerPrev)
  93. super.viewDidLoad()
  94. self.loadPhoto(id: photoId)
  95. // Set button action
  96. self.barButton.addTarget(self, action: #selector(self.back), for: .touchUpInside)
  97. }
  98. /**
  99. Dismisses the controller.
  100. */
  101. func back() {
  102. NSLog(":PHOTOCONTROLLER:DEBUG: Back")
  103. self.dismiss(animated: true, completion: nil)
  104. }
  105. /**
  106. Dispose of any resources that can be recreated.
  107. */
  108. override func didReceiveMemoryWarning() {
  109. super.didReceiveMemoryWarning()
  110. }
  111. /**
  112. Opens the next photo.
  113. */
  114. func nextPhoto(_ sender:UITapGestureRecognizer? = nil){
  115. photoIdx = photoIdx + 1
  116. loadPhoto(id: photoIds[photoIdx])
  117. }
  118. /**
  119. Opens the previous photo.
  120. */
  121. func prevPhoto(_ sender:UITapGestureRecognizer? = nil){
  122. photoIdx = photoIdx - 1
  123. loadPhoto(id: photoIds[photoIdx])
  124. }
  125. /**
  126. Loads a photo in the viewer.
  127. :param: id
  128. */
  129. public func loadPhoto(id: Int){
  130. let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  131. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  132. let lang : String = getLanguage()
  133. context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
  134. let fetchRequest: NSFetchRequest<Photo> = Photo.fetchRequest()
  135. fetchRequest.predicate = NSPredicate(format: "id = %i", id)
  136. do {
  137. let searchResults = try context.fetch(fetchRequest)
  138. var sTitle: String
  139. var sText: String
  140. var image: String
  141. var date: NSDate
  142. for r in searchResults as [NSManagedObject] {
  143. sTitle = r.value(forKey: "title_\(lang)")! as! String
  144. if sTitle == "" || sTitle == "ul" {
  145. sTitle = self.albumTitle
  146. }
  147. self.photoTitle.text = " \(sTitle.decode().stripHtml())"
  148. // Enable or disable buttons
  149. if photoIdx == 0{
  150. self.btPrev.isEnabled = false
  151. self.btPrev.alpha = 0.5
  152. }
  153. else{
  154. self.btPrev.isEnabled = true
  155. self.btPrev.alpha = 1
  156. }
  157. if photoIdx == photoIds.count - 1{
  158. self.btNext.isEnabled = false
  159. self.btNext.alpha = 0.5
  160. }
  161. else{
  162. self.btNext.isEnabled = true
  163. self.btNext.alpha = 1
  164. }
  165. // Get image
  166. image = ""
  167. let imgFetchRequest: NSFetchRequest<Photo> = Photo.fetchRequest()
  168. imgFetchRequest.predicate = NSPredicate(format: "id == %i", id)
  169. do{
  170. let imgSearchResults = try context.fetch(imgFetchRequest)
  171. let r: NSManagedObject = imgSearchResults[0]
  172. image = r.value(forKey: "file")! as! String
  173. date = r.value(forKey: "uploaded")! as! NSDate
  174. let path = "img/galeria/preview/\(image)"
  175. // TODO: Every time, set placeholder image
  176. self.photoImage.setImage(localPath: path, remotePath: "https://margolariak.com/\(path)")
  177. self.photoDate.text = formatDate(date: date, lang: lang)
  178. }
  179. catch {
  180. NSLog(":PHOTO:ERROR: Error getting image for post \(id): \(error)")
  181. }
  182. }
  183. } catch {
  184. NSLog(":PHOTO:ERROR: Error setting up photo \(id): \(error)")
  185. }
  186. }
  187. /**
  188. Formats a date to the desired language.
  189. :param: text The date.
  190. :param: lang Device language (only 'es', 'en', or 'eu').
  191. */
  192. func formatDate(date: NSDate, lang: String) -> String{
  193. let months_es = ["0index", "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"]
  194. let months_en = ["0index", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
  195. let months_eu = ["0index", "urtarrilaren", "otsailaren", "martxoaren", "abrilaren", "maiatzaren", "ekainaren", "ustailaren", "abustuaren", "irailaren", "urriaren", "azaroaren", "abenduaren"]
  196. let days_es = ["0index", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sábado", "Domingo"]
  197. let days_en = ["0index", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
  198. let days_eu = ["0index", "Astelehena", "Asteartea", "Asteazkena", "Osteguna", "Ostirala", "Larumbata", "Igandea"]
  199. let calendar = Calendar.current
  200. let year = calendar.component(.year, from: date as Date)
  201. let day = calendar.component(.day, from: date as Date)
  202. let month = calendar.component(.month, from: date as Date)
  203. let weekday = calendar.component(.weekday, from: date as Date)
  204. var strDate = ""
  205. switch lang{
  206. case "en":
  207. var dayNum = ""
  208. switch day{
  209. case 1:
  210. dayNum = "1th"
  211. break
  212. case 2:
  213. dayNum = "2nd"
  214. break;
  215. case 3:
  216. dayNum = "3rd"
  217. break;
  218. default:
  219. dayNum = "\(weekday)th"
  220. }
  221. strDate = "\(days_en[weekday]), \(months_en[month]) \(dayNum), \(year)"
  222. break
  223. case "eu":
  224. strDate = "\(year)ko \(days_eu[weekday]) \(months_eu[month]) \(day)an"
  225. break
  226. default:
  227. strDate = "\(days_es[weekday]) \(day) de \(months_es[month]) de \(year)"
  228. }
  229. return strDate
  230. }
  231. /**
  232. Gets the device language. The only recognized languages are Spanish, English and Basque.
  233. If the device has another language, Spanish will be selected by default.
  234. :return: Two-letter language code.
  235. */
  236. func getLanguage() -> String{
  237. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  238. if(pre == "es" || pre == "en" || pre == "eu"){
  239. return pre
  240. }
  241. else{
  242. return "es"
  243. }
  244. }
  245. }