BlogView.swift 6.2 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 BlogView: UIView {
  27. // Outlets
  28. @IBOutlet weak var scrollView: UIScrollView!
  29. @IBOutlet var container: UIView!
  30. @IBOutlet weak var section: Section!
  31. var delegate: AppDelegate? = nil
  32. var postList: UIStackView? = nil
  33. var storyboard: UIStoryboard? = nil
  34. var controller: ViewController? = nil
  35. var context: NSManagedObjectContext? = nil;
  36. var lang: String? = nil
  37. override init(frame: CGRect){
  38. super.init(frame: frame)
  39. }
  40. /**
  41. Run when the view is started.
  42. */
  43. required init?(coder aDecoder: NSCoder) {
  44. super.init(coder: aDecoder)
  45. NSLog(":BLOG:DEBUG: init (coder).")
  46. // Load the contents of the HomeView.xib file.
  47. Bundle.main.loadNibNamed("BlogView", owner: self, options: nil)
  48. self.addSubview(self.container)
  49. self.container.frame = self.bounds
  50. self.section.setTitle(text: "Blog")
  51. self.postList = self.section.getContentStack()
  52. // Get viewController from StoryBoard
  53. self.storyboard = UIStoryboard(name: "Main", bundle: nil)
  54. self.controller = storyboard?.instantiateViewController(withIdentifier: "GMViewController") as! ViewController
  55. self.context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  56. self.delegate = UIApplication.shared.delegate as! AppDelegate
  57. self.lang = getLanguage()
  58. self.context?.persistentStoreCoordinator = delegate?.persistentStoreCoordinator
  59. populate()
  60. NSLog(":BLOG:DEBUG: Finished loading BlogView")
  61. }
  62. func populate(){
  63. let fetchRequest: NSFetchRequest<Post> = Post.fetchRequest()
  64. let sortDescriptor = NSSortDescriptor(key: "dtime", ascending: false)
  65. let sortDescriptors = [sortDescriptor]
  66. fetchRequest.sortDescriptors = sortDescriptors
  67. do {
  68. //go get the results
  69. let searchResults = try self.context?.fetch(fetchRequest)
  70. //I like to check the size of the returned results!
  71. NSLog(":BLOG:DEBUG: Total posts: \(searchResults?.count)")
  72. var row : RowBlog
  73. var count = 0
  74. var id: Int
  75. var title: String
  76. var text: String
  77. var image: String
  78. //You need to convert to NSManagedObject to use 'for' loops
  79. for r in searchResults as! [NSManagedObject] {
  80. count = count + 1
  81. //get the Key Value pairs (although there may be a better way to do that...
  82. NSLog(":BLOG:DEBUG: Post perm: \(r.value(forKey: "permalink"))")
  83. //Create a new row
  84. row = RowBlog.init(s: "rowBlog\(count)", i: count)
  85. id = r.value(forKey: "id")! as! Int
  86. title = r.value(forKey: "title_\(lang!)")! as! String
  87. text = r.value(forKey: "text_\(lang!)")! as! String
  88. row.setTitle(text: title)
  89. row.setText(text: text)
  90. // Get main image
  91. image = ""
  92. let imgFetchRequest: NSFetchRequest<Post_image> = Post_image.fetchRequest()
  93. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  94. let imgSortDescriptors = [imgSortDescriptor]
  95. imgFetchRequest.sortDescriptors = imgSortDescriptors
  96. imgFetchRequest.predicate = NSPredicate(format: "post == %i", id)
  97. imgFetchRequest.fetchLimit = 1
  98. do{
  99. let imgSearchResults = try context?.fetch(imgFetchRequest)
  100. for imgR in imgSearchResults as! [NSManagedObject]{
  101. image = imgR.value(forKey: "image")! as! String
  102. NSLog(":BLOG:DEBUG: Image: \(image)")
  103. row.setImage(filename: image)
  104. }
  105. } catch {
  106. NSLog(":BLOG:ERROR: Error getting image for post \(id): \(error)")
  107. }
  108. print("BLOG:DEBUG: Row height: \(row.frame.height)")
  109. self.postList?.addArrangedSubview(row)
  110. row.setNeedsLayout()
  111. row.layoutIfNeeded()
  112. // TODO: Do this on the row didLoad method
  113. // Set tap recognizer
  114. //let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(openPost(_:)))
  115. //row.isUserInteractionEnabled = true
  116. //row.addGestureRecognizer(tapRecognizer)
  117. }
  118. } catch {
  119. NSLog(":BLOG:ERROR: Error with request: \(error)")
  120. }
  121. //Always at the end: update scrollview
  122. //var h: Int = 0
  123. //for view in scrollView.subviews {
  124. // //contentRect = contentRect.union(view.frame);
  125. // h = h + Int(view.frame.height) + 30 //Why 30?
  126. // NSLog(":BLOG:DEBUG: curh: \(h)")
  127. //}
  128. // TODO: Calculate at the end
  129. //self.scrollView.contentSize.height = 2500//CGFloat(h);
  130. // The view controller
  131. //var viewController: ViewController = self.window?.rootViewController as! ViewController
  132. //let viewController = UIApplication.topViewController() as! ViewController
  133. //viewController.showPost(id: 4)
  134. //print("BLOG:DEBUG: Show post on load.")
  135. //self.delegate?.controller?.showPost(id: 4)
  136. //controller.showPost(id: 4)
  137. NSLog(":BLOG:DEBUG: Finished populating BlogView")
  138. }
  139. /*func openPost(){//(_ sender:UITapGestureRecognizer? = nil){
  140. print("BLOG:DEBUG: getting delegate and showing post.")
  141. let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
  142. delegate.controller?.showPost(id: 4)
  143. print("BLOG:DEBUG: Post should be shown.")
  144. }
  145. func openPost(_ sender:UITapGestureRecognizer? = nil){
  146. print("BLOG:DEBUG: getting delegate and showing post.")
  147. let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
  148. delegate.controller?.showPost(id: 4)
  149. print("BLOG:DEBUG: Post should be shown.")
  150. }*/
  151. func getLanguage() -> String{
  152. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  153. if(pre == "es" || pre == "en" || pre == "eu"){
  154. return pre
  155. }
  156. else{
  157. return "es"
  158. }
  159. }
  160. }