khenid

Untitled

Feb 4th, 2015
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.46 KB | None | 0 0
  1. //
  2. // TableViewController.swift
  3. // CheapEat
  4. //
  5. // Created by Johnathon Moss on 14/01/2015.
  6. // Copyright (c) 2015 CheapEat. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import CoreLocation
  11.  
  12. class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate {
  13.  
  14. @IBOutlet weak var tableView: UITableView!
  15. @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
  16. @IBOutlet weak var noDealsFoundLabel: UILabel!
  17. @IBOutlet weak var activityBG: UIImageView!
  18.  
  19.  
  20. var deals:[Deal] = [Deal]()
  21. let model:DealModel = DealModel()
  22. var imageCache = [String : UIImage]()
  23.  
  24. var lat:String = ""
  25. var lng:String = ""
  26.  
  27. var locationManager = CLLocationManager()
  28.  
  29. // Values for nextView
  30.  
  31. var restaurantDictionarys = [NSDictionary]()
  32. var ids = [String]()
  33. var restaurantsName = [String]()
  34. var restaurantsAdd = [String]()
  35. var venueInfo = [String]()
  36. var resLats = [String]()
  37. var resLng = [String]()
  38. var resPhone = [String]()
  39. var i = 0
  40.  
  41. override func viewDidLoad() {
  42. super.viewDidLoad()
  43.  
  44. self.tableView.delegate = self
  45. self.tableView.dataSource = self
  46. // Do any additional setup after loading the view.
  47.  
  48. // Set nav bar title (so back button says "Deals")
  49. self.navigationItem.title = "Deals"
  50.  
  51. activityIndicator.hidden = false
  52. activityBG.hidden = false
  53.  
  54. // Core Location
  55.  
  56. locationManager.delegate = self
  57. locationManager.desiredAccuracy = kCLLocationAccuracyBest
  58. locationManager.requestWhenInUseAuthorization()
  59. locationManager.startUpdatingLocation()
  60.  
  61. //add logo to nav bar
  62. let navBarLogo: UIImageView = UIImageView(frame: CGRectMake(0, 0, 120, 36))
  63. navBarLogo.image = UIImage(named: "logo")
  64. self.navigationItem.titleView = navBarLogo
  65.  
  66.  
  67. self.tableView.delegate = self
  68. self.tableView.dataSource = self
  69.  
  70. //remove table view insets
  71. self.tableView.layoutMargins = UIEdgeInsetsZero
  72. }
  73.  
  74. func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
  75.  
  76. println(indexPath.row)
  77. let VenueData = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewController") as VenueDetailViewController
  78. VenueData.venueID = self.ids[indexPath.row]
  79. self.navigationController?.pushViewController(VenueData, animated: true)
  80. }
  81.  
  82. func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
  83.  
  84.  
  85. var userLocation:CLLocation = locations[0] as CLLocation
  86.  
  87. var latitude:String = "-34.424599"//"\(userLocation.coordinate.latitude)"
  88. var longitude:String = "150.880587"//"\(userLocation.coordinate.longitude)"
  89.  
  90. locationManager.stopUpdatingLocation()
  91.  
  92.  
  93. self.lat = latitude
  94. self.lng = longitude
  95.  
  96. println(self.lat)
  97. println(self.lng)
  98.  
  99.  
  100.  
  101. // Get the deals from the deal model
  102. self.deals = getDeals()
  103.  
  104. if self.deals.count > 0 {
  105.  
  106. activityIndicator.stopAnimating()
  107. activityIndicator.hidden = true
  108. activityBG.hidden = true
  109. self.tableView.reloadData()
  110.  
  111. }
  112. else {
  113. noDealsFoundLabel.hidden = false
  114. activityIndicator.stopAnimating()
  115. activityIndicator.hidden = true
  116. activityBG.hidden = true
  117.  
  118. }
  119. }
  120.  
  121. func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
  122. println(error)
  123.  
  124. activityIndicator.stopAnimating()
  125. activityIndicator.hidden = true
  126. activityBG.hidden = true
  127.  
  128. var alert = UIAlertController(title: "Location issue", message: "Sorry, we need to know your location to show you the nearest deals. Please turn on location services for CheapEat in settings.", preferredStyle: UIAlertControllerStyle.Alert)
  129. alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
  130. self.presentViewController(alert, animated: true, completion: nil)
  131. }
  132.  
  133. override func didReceiveMemoryWarning() {
  134. super.didReceiveMemoryWarning()
  135. // Dispose of any resources that can be recreated.
  136. }
  137.  
  138. func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  139.  
  140. return self.deals.count
  141. }
  142.  
  143. func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  144.  
  145. // try to reuse cell
  146. let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("DealCell") as UITableViewCell
  147.  
  148. // get the deal image
  149. let currentImage = deals[indexPath.row].imageID
  150. let unwrappedImage = currentImage
  151. var image = self.imageCache[unwrappedImage]
  152. let imageUrl = NSURL(string: "http://staging.api.cheapeat.com.au/deals/\(unwrappedImage)/photo")
  153. //let imageData = NSData(contentsOfURL: imageUrl!)
  154.  
  155. // access the elements using tag
  156. var dealImage:UIImageView = cell.viewWithTag(1) as UIImageView
  157. var title:UILabel = cell.viewWithTag(2) as UILabel
  158. var price:UILabel = cell.viewWithTag(3) as UILabel
  159. var location:UILabel = cell.viewWithTag(4) as UILabel
  160. var days:UILabel = cell.viewWithTag(5) as UILabel
  161. var time:UILabel = cell.viewWithTag(6) as UILabel
  162. var venue:UIButton = cell.viewWithTag(7) as UIButton
  163.  
  164. // reset reused cell image to placeholder
  165. dealImage.image = UIImage(named: "placeholder")
  166.  
  167. // async image
  168. if image == nil {
  169.  
  170. let request: NSURLRequest = NSURLRequest(URL: imageUrl!)
  171.  
  172. NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
  173. if error == nil {
  174.  
  175. image = UIImage(data: data)
  176.  
  177. self.imageCache[unwrappedImage] = image
  178. dispatch_async(dispatch_get_main_queue(), {
  179. dealImage.image = image
  180.  
  181. })
  182. }
  183. else {
  184.  
  185. }
  186. })
  187. }
  188.  
  189. else{
  190. dealImage.image = image
  191. }
  192.  
  193. // set the cell properties
  194. let currentDealToDisplay:Deal = self.deals[indexPath.row]
  195. //dealImage.image = UIImage(data: imageData!)
  196. title.text = " " + currentDealToDisplay.title + " "
  197. price.text = "$" + currentDealToDisplay.price.stringByTrimmingCharactersInSet(NSCharacterSet.punctuationCharacterSet())
  198.  
  199. /*
  200.  
  201. var cleanedUpDays = currentDealToDisplay.days.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
  202. days.text = cleanedUpDays.stringByTrimmingCharactersInSet(NSCharacterSet.punctuationCharacterSet())
  203.  
  204. var cleanedUpTime = currentDealToDisplay.time.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
  205. time.text = cleanedUpTime.stringByTrimmingCharactersInSet(NSCharacterSet.punctuationCharacterSet())
  206.  
  207. */
  208.  
  209. location.text = currentDealToDisplay.location
  210. venue.setTitle("\(currentDealToDisplay.location)", forState: UIControlState.Normal)
  211.  
  212.  
  213.  
  214. // remove table view insets
  215. cell.layoutMargins = UIEdgeInsetsZero
  216.  
  217. return cell
  218.  
  219. }
  220.  
  221. func getDeals() -> [Deal] {
  222.  
  223. // Array of deal objects
  224. var deals:[Deal] = [Deal]()
  225.  
  226. // Get Json array of dictionaries
  227. let jsonObjects:[NSDictionary] = self.getRemoteJsonFile()
  228.  
  229. // Loop through each dictionary and assign values to our deal objs
  230. var index:Int
  231. self.ids = [String]()
  232. self.restaurantsName = [String]()
  233. self.restaurantsAdd = [String]()
  234. self.venueInfo = [String]()
  235. self.resLats = [String]()
  236. self.resLng = [String]()
  237. self.resPhone = [String]()
  238. for index = 0; index < jsonObjects.count; index++ {
  239.  
  240. // Current JSON dict
  241. let jsonDictionary:NSDictionary = jsonObjects[index]
  242.  
  243. self.restaurantDictionarys = jsonDictionary["restaurants"] as [NSDictionary]
  244.  
  245. // Create a deal obj
  246. var q:Deal = Deal()
  247.  
  248. // Assign the values of each key value pair to the deal object
  249. q.title = jsonDictionary["name"] as String
  250. q.price = jsonDictionary["price_data"] as String
  251. q.imageID = jsonDictionary["id"] as String
  252. q.location = restaurantDictionarys[0]["name"] as String
  253. q.latitude = restaurantDictionarys[0]["lat"] as String
  254. q.longitude = restaurantDictionarys[0]["lng"] as String
  255. q.days = jsonDictionary["availability_day"] as String
  256. q.time = jsonDictionary["availability_time"] as String
  257. /*q.answers = jsonDictionary["answers"] as [String]
  258. q.correctAnswerIndex = jsonDictionary["correctIndex"] as Int
  259. q.module = jsonDictionary["module"] as Int
  260. q.lesson = jsonDictionary["lesson"] as Int
  261. q.feedback = jsonDictionary["feedback"] as String*/
  262.  
  263. for values in restaurantDictionarys{
  264.  
  265. var id : String = restaurantDictionarys[self.i]["id"] as String
  266. var name : String = restaurantDictionarys[self.i]["name"] as String
  267. var address : String = restaurantDictionarys[self.i]["friendly_address"] as String
  268. if let venue = restaurantDictionarys[self.i]["description"] as? String{
  269.  
  270. self.venueInfo.append(venue)
  271. }else{
  272.  
  273. self.venueInfo.append("No Description")
  274. }
  275.  
  276. if let phone = restaurantDictionarys[self.i]["phone"] as? String{
  277.  
  278. self.resPhone.append(phone)
  279.  
  280. }else{
  281.  
  282. self.resPhone.append("")
  283. }
  284.  
  285. var lat : String = restaurantDictionarys[self.i]["lat"] as String
  286. var lng : String = restaurantDictionarys[self.i]["lng"] as String
  287. self.ids.append(id)
  288. self.restaurantsName.append(name)
  289. self.restaurantsAdd.append(address)
  290. self.resLats.append(lat)
  291. self.resLng.append(lng)
  292. }
  293.  
  294. // Add the question to the question array
  295. deals.append(q)
  296. }
  297.  
  298. // Return list of question objects
  299. return deals
  300.  
  301. }
  302.  
  303. func getRemoteJsonFile() -> [NSDictionary] {
  304.  
  305. // Create a new URL
  306. let remoteUrl:NSURL? = NSURL(string: "http://staging.api.cheapeat.com.au/search?lat=\(self.lat)&lng=\(self.lng)")
  307.  
  308. let urlString:String = "\(remoteUrl)"
  309. println(urlString)
  310.  
  311. // Check if it's nil
  312. if let actualRemoteUrl = remoteUrl {
  313.  
  314. // Try to get the data
  315. let fileData:NSData? = NSData(contentsOfURL: actualRemoteUrl)
  316.  
  317. // Check if it's nil
  318. if let actualFileData = fileData {
  319.  
  320. // Parse out the dictionaries
  321. let arrayOfDictionaries:[NSDictionary]? = NSJSONSerialization.JSONObjectWithData(actualFileData, options: NSJSONReadingOptions.MutableContainers, error: nil) as [NSDictionary]?
  322.  
  323. if let actualArrayOfDictionaries = arrayOfDictionaries {
  324.  
  325. // Successfully parsed out array of dictionaries
  326. return actualArrayOfDictionaries
  327. }
  328. }
  329.  
  330. }
  331. return [NSDictionary]()
  332. }
  333. }
Advertisement
Add Comment
Please, Sign In to add comment