khenid

Untitled

Feb 5th, 2015
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.81 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.dataSource = self
  45. self.tableView.delegate = 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. self.performSegueWithIdentifier("Detail", sender: self)
  77. }
  78.  
  79. override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  80.  
  81. if (segue.identifier == "Detail") {
  82.  
  83. var viewController = segue.destinationViewController as VenueDetailViewController
  84. let indexPath = self.tableView.indexPathForSelectedRow()?.row
  85. println(indexPath)
  86.  
  87. }
  88. }
  89.  
  90.  
  91. func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
  92.  
  93.  
  94. var userLocation:CLLocation = locations[0] as CLLocation
  95.  
  96. var latitude:String = "-34.4232722"//"\(userLocation.coordinate.latitude)"
  97. var longitude:String = "150.8865837"//"\(userLocation.coordinate.longitude)"
  98.  
  99. // var latitude:String = "\(userLocation.coordinate.latitude)"
  100. // var longitude:String = "\(userLocation.coordinate.longitude)"
  101.  
  102. locationManager.stopUpdatingLocation()
  103.  
  104.  
  105. self.lat = latitude
  106. self.lng = longitude
  107.  
  108. println(self.lat)
  109. println(self.lng)
  110.  
  111.  
  112.  
  113. // Get the deals from the deal model
  114. self.deals = getDeals()
  115.  
  116. if self.deals.count > 0 {
  117.  
  118. activityIndicator.stopAnimating()
  119. activityIndicator.hidden = true
  120. activityBG.hidden = true
  121. self.tableView.reloadData()
  122.  
  123. }
  124. else {
  125. noDealsFoundLabel.hidden = false
  126. activityIndicator.stopAnimating()
  127. activityIndicator.hidden = true
  128. activityBG.hidden = true
  129.  
  130. }
  131. }
  132.  
  133. func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
  134. println(error)
  135.  
  136. activityIndicator.stopAnimating()
  137. activityIndicator.hidden = true
  138. activityBG.hidden = true
  139.  
  140. 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)
  141. alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
  142. self.presentViewController(alert, animated: true, completion: nil)
  143. }
  144.  
  145. override func didReceiveMemoryWarning() {
  146. super.didReceiveMemoryWarning()
  147. // Dispose of any resources that can be recreated.
  148. }
  149.  
  150. func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  151.  
  152. return self.deals.count
  153. }
  154.  
  155. func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  156.  
  157. // try to reuse cell
  158. let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("DealCell") as UITableViewCell
  159.  
  160. // get the deal image
  161. let currentImage = deals[indexPath.row].imageID
  162. let unwrappedImage = currentImage
  163. var image = self.imageCache[unwrappedImage]
  164. let imageUrl = NSURL(string: "http://staging.api.cheapeat.com.au/deals/\(unwrappedImage)/photo")
  165. //let imageData = NSData(contentsOfURL: imageUrl!)
  166.  
  167. // access the elements using tag
  168. var dealImage:UIImageView = cell.viewWithTag(1) as UIImageView
  169. var title:UILabel = cell.viewWithTag(2) as UILabel
  170. var price:UILabel = cell.viewWithTag(3) as UILabel
  171. var location:UILabel = cell.viewWithTag(4) as UILabel
  172. var days:UILabel = cell.viewWithTag(5) as UILabel
  173. var time:UILabel = cell.viewWithTag(6) as UILabel
  174. var venue:UIButton = cell.viewWithTag(7) as UIButton
  175.  
  176. // reset reused cell image to placeholder
  177. dealImage.image = UIImage(named: "placeholder")
  178.  
  179. // async image
  180. if image == nil {
  181.  
  182. let request: NSURLRequest = NSURLRequest(URL: imageUrl!)
  183.  
  184. NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
  185. if error == nil {
  186.  
  187. image = UIImage(data: data)
  188.  
  189. self.imageCache[unwrappedImage] = image
  190. dispatch_async(dispatch_get_main_queue(), {
  191. dealImage.image = image
  192.  
  193. })
  194. }
  195. else {
  196.  
  197. }
  198. })
  199. }
  200.  
  201. else{
  202. dealImage.image = image
  203. }
  204.  
  205. // set the cell properties
  206. let currentDealToDisplay:Deal = self.deals[indexPath.row]
  207. //dealImage.image = UIImage(data: imageData!)
  208. title.text = " " + currentDealToDisplay.title + " "
  209. price.text = "$" + currentDealToDisplay.price.stringByTrimmingCharactersInSet(NSCharacterSet.punctuationCharacterSet())
  210.  
  211. /*
  212.  
  213. var cleanedUpDays = currentDealToDisplay.days.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
  214. days.text = cleanedUpDays.stringByTrimmingCharactersInSet(NSCharacterSet.punctuationCharacterSet())
  215.  
  216. var cleanedUpTime = currentDealToDisplay.time.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
  217. time.text = cleanedUpTime.stringByTrimmingCharactersInSet(NSCharacterSet.punctuationCharacterSet())
  218.  
  219. */
  220.  
  221. location.text = currentDealToDisplay.location
  222. venue.setTitle("\(currentDealToDisplay.location)", forState: UIControlState.Normal)
  223.  
  224. venue.tag = indexPath.row
  225.  
  226. // remove table view insets
  227. cell.layoutMargins = UIEdgeInsetsZero
  228.  
  229. return cell
  230.  
  231. }
  232.  
  233. func getDeals() -> [Deal] {
  234.  
  235. // Array of deal objects
  236. var deals:[Deal] = [Deal]()
  237.  
  238. // Get Json array of dictionaries
  239. let jsonObjects:[NSDictionary] = self.getRemoteJsonFile()
  240.  
  241. // Loop through each dictionary and assign values to our deal objs
  242. var index:Int
  243. self.ids = [String]()
  244. self.restaurantsName = [String]()
  245. self.restaurantsAdd = [String]()
  246. self.venueInfo = [String]()
  247. self.resLats = [String]()
  248. self.resLng = [String]()
  249. self.resPhone = [String]()
  250. for index = 0; index < jsonObjects.count; index++ {
  251.  
  252. // Current JSON dict
  253. let jsonDictionary:NSDictionary = jsonObjects[index]
  254.  
  255. self.restaurantDictionarys = jsonDictionary["restaurants"] as [NSDictionary]
  256.  
  257. // Create a deal obj
  258. var q:Deal = Deal()
  259.  
  260. // Assign the values of each key value pair to the deal object
  261. q.title = jsonDictionary["name"] as String
  262. q.price = jsonDictionary["price_data"] as String
  263. q.imageID = jsonDictionary["id"] as String
  264. q.location = restaurantDictionarys[0]["name"] as String
  265. q.latitude = restaurantDictionarys[0]["lat"] as String
  266. q.longitude = restaurantDictionarys[0]["lng"] as String
  267. q.days = jsonDictionary["availability_day"] as String
  268. q.time = jsonDictionary["availability_time"] as String
  269. /*q.answers = jsonDictionary["answers"] as [String]
  270. q.correctAnswerIndex = jsonDictionary["correctIndex"] as Int
  271. q.module = jsonDictionary["module"] as Int
  272. q.lesson = jsonDictionary["lesson"] as Int
  273. q.feedback = jsonDictionary["feedback"] as String*/
  274.  
  275. for values in restaurantDictionarys{
  276.  
  277. var id : String = restaurantDictionarys[self.i]["id"] as String
  278. var name : String = restaurantDictionarys[self.i]["name"] as String
  279. var address : String = restaurantDictionarys[self.i]["friendly_address"] as String
  280. if let venue = restaurantDictionarys[self.i]["description"] as? String{
  281.  
  282. self.venueInfo.append(venue)
  283. }else{
  284.  
  285. self.venueInfo.append("No Description")
  286. }
  287.  
  288. if let phone = restaurantDictionarys[self.i]["phone"] as? String{
  289.  
  290. self.resPhone.append(phone)
  291.  
  292. }else{
  293.  
  294. self.resPhone.append("Not Available")
  295. }
  296.  
  297. var lat : String = restaurantDictionarys[self.i]["lat"] as String
  298. var lng : String = restaurantDictionarys[self.i]["lng"] as String
  299. self.ids.append(id)
  300. self.restaurantsName.append(name)
  301. self.restaurantsAdd.append(address)
  302. self.resLats.append(lat)
  303. self.resLng.append(lng)
  304. }
  305.  
  306. // Add the question to the question array
  307. deals.append(q)
  308. }
  309.  
  310. // Return list of question objects
  311. return deals
  312.  
  313. }
  314.  
  315. func getRemoteJsonFile() -> [NSDictionary] {
  316.  
  317. // Create a new URL
  318. let remoteUrl:NSURL? = NSURL(string: "http://staging.api.cheapeat.com.au/search?lat=\(self.lat)&lng=\(self.lng)")
  319.  
  320. let urlString:String = "\(remoteUrl)"
  321. println(urlString)
  322.  
  323. // Check if it's nil
  324. if let actualRemoteUrl = remoteUrl {
  325.  
  326. // Try to get the data
  327. let fileData:NSData? = NSData(contentsOfURL: actualRemoteUrl)
  328.  
  329. // Check if it's nil
  330. if let actualFileData = fileData {
  331.  
  332. // Parse out the dictionaries
  333. let arrayOfDictionaries:[NSDictionary]? = NSJSONSerialization.JSONObjectWithData(actualFileData, options: NSJSONReadingOptions.MutableContainers, error: nil) as [NSDictionary]?
  334.  
  335. if let actualArrayOfDictionaries = arrayOfDictionaries {
  336.  
  337. // Successfully parsed out array of dictionaries
  338. return actualArrayOfDictionaries
  339. }
  340. }
  341.  
  342. }
  343. return [NSDictionary]()
  344. }
  345. }
Advertisement
Add Comment
Please, Sign In to add comment