PhotoViewController.swift 8.5 KB

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