PhotoViewController.swift 8.4 KB

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