PhotoViewController.swift 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. // 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(":GALLERYCONTROLLER: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
  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. sTitle = r.value(forKey: "title_\(lang)")! as! String
  141. if sTitle == "" || sTitle == "ul" {
  142. sTitle = self.albumTitle
  143. }
  144. self.photoTitle.text = " \(sTitle.decode().stripHtml())"
  145. // Enable or disable buttons
  146. if photoIdx == 0{
  147. self.btPrev.isEnabled = false
  148. self.btPrev.alpha = 0.5
  149. }
  150. else{
  151. self.btPrev.isEnabled = true
  152. self.btPrev.alpha = 1
  153. }
  154. if photoIdx == photoIds.count - 1{
  155. self.btNext.isEnabled = false
  156. self.btNext.alpha = 0.5
  157. }
  158. else{
  159. self.btNext.isEnabled = true
  160. self.btNext.alpha = 1
  161. }
  162. // Get image
  163. image = ""
  164. let imgFetchRequest: NSFetchRequest<Photo> = Photo.fetchRequest()
  165. imgFetchRequest.predicate = NSPredicate(format: "id == %i", id)
  166. do{
  167. let imgSearchResults = try context.fetch(imgFetchRequest)
  168. let r: NSManagedObject = imgSearchResults[0]
  169. image = r.value(forKey: "file")! as! String
  170. date = r.value(forKey: "uploaded")! as! NSDate
  171. let path = "img/galeria/preview/\(image)"
  172. // TODO: Every time, set placeholder image
  173. self.photoImage.setImage(localPath: path, remotePath: "https://margolariak.com/\(path)")
  174. self.photoDate.text = formatDate(date: date, lang: lang)
  175. }
  176. catch {
  177. NSLog(":PHOTO:ERROR: Error getting image for post \(id): \(error)")
  178. }
  179. }
  180. } catch {
  181. NSLog(":PHOTO:ERROR: Error setting up photo \(id): \(error)")
  182. }
  183. }
  184. /**
  185. Formats a date to the desired language.
  186. :param: text The date.
  187. :param: lang Device language (only 'es', 'en', or 'eu').
  188. */
  189. func formatDate(date: NSDate, lang: String) -> String{
  190. let months_es = ["0index", "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"]
  191. let months_en = ["0index", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
  192. let months_eu = ["0index", "urtarrilaren", "otsailaren", "martxoaren", "abrilaren", "maiatzaren", "ekainaren", "ustailaren", "abustuaren", "irailaren", "urriaren", "azaroaren", "abenduaren"]
  193. let days_es = ["0index", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sábado", "Domingo"]
  194. let days_en = ["0index", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
  195. let days_eu = ["0index", "Astelehena", "Asteartea", "Asteazkena", "Osteguna", "Ostirala", "Larumbata", "Igandea"]
  196. let calendar = Calendar.current
  197. let year = calendar.component(.year, from: date as Date)
  198. let day = calendar.component(.day, from: date as Date)
  199. let month = calendar.component(.month, from: date as Date)
  200. let weekday = calendar.component(.weekday, from: date as Date)
  201. var strDate = ""
  202. switch lang{
  203. case "en":
  204. var dayNum = ""
  205. switch day{
  206. case 1:
  207. dayNum = "1th"
  208. break
  209. case 2:
  210. dayNum = "2nd"
  211. break;
  212. case 3:
  213. dayNum = "3rd"
  214. break;
  215. default:
  216. dayNum = "\(weekday)th"
  217. }
  218. strDate = "\(days_en[weekday]), \(months_en[month]) \(dayNum), \(year)"
  219. break
  220. case "eu":
  221. strDate = "\(year)ko \(days_eu[weekday]) \(months_eu[month]) \(day)an"
  222. break
  223. default:
  224. strDate = "\(days_es[weekday]) \(day) de \(months_es[month]) de \(year)"
  225. }
  226. return strDate
  227. }
  228. /**
  229. Gets the device language. The only recognized languages are Spanish, English and Basque.
  230. If the device has another language, Spanish will be selected by default.
  231. :return: Two-letter language code.
  232. */
  233. func getLanguage() -> String{
  234. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  235. if(pre == "es" || pre == "en" || pre == "eu"){
  236. return pre
  237. }
  238. else{
  239. return "es"
  240. }
  241. }
  242. }