khenid

Untitled

Feb 16th, 2015
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  MapViewController.swift
  3. //  CheapEat
  4. //
  5. //  Created by Johnathon Moss on 16/01/2015.
  6. //  Copyright (c) 2015 CheapEat. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import MapKit
  11. import CoreLocation
  12.  
  13. class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
  14.  
  15.     @IBOutlet weak var mapView: MKMapView!
  16.    
  17.     var latArray = [String]()
  18.     var lngArray = [String]()
  19.     var resName = [String]()
  20.    
  21.     var deals:[Deal] = [Deal]()
  22.     let model:DealModel = DealModel()
  23.    
  24.     var lat:String = ""
  25.     var lng:String = ""
  26.  
  27.     var manager = CLLocationManager()
  28.    
  29.     override func viewDidLoad() {
  30.         super.viewDidLoad()
  31.  
  32.         // Do any additional setup after loading the view.
  33.        
  34.        
  35.         //add logo to nav bar
  36.         let navBarLogo: UIImageView = UIImageView(frame: CGRectMake(0, 0, 120, 36))
  37.         navBarLogo.image = UIImage(named: "logo")
  38.         self.navigationItem.titleView = navBarLogo
  39.        
  40.         // Core Location
  41.         manager.delegate = self
  42.         manager.desiredAccuracy = kCLLocationAccuracyBest
  43.         manager.requestWhenInUseAuthorization()
  44.         manager.startUpdatingLocation()
  45.        
  46.         // show user location on map
  47. //        mapView.showsUserLocation = true
  48.        
  49.         // this combined with manager.stopUpdatingLocation fixed map snapping back issue
  50. //        mapView.userLocation
  51.        
  52.        
  53.         // -34.426298, 150.892260
  54.        
  55.         /*
  56.         var latitude:CLLocationDegrees = -34.426298
  57.         var longitude:CLLocationDegrees = 150.89226
  58.        
  59.         var latDelta:CLLocationDegrees = 0.03
  60.         var lonDelta:CLLocationDegrees = 0.03
  61.        
  62.         var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
  63.         var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
  64.        
  65.         var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
  66.        
  67.         mapView.setRegion(region, animated: true)
  68.         */
  69.        
  70.         // add annotations to map
  71.        
  72.     }
  73.    
  74.     func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
  75.        
  76.        
  77. //        var userLocation:CLLocation = locations[0] as CLLocation
  78.        
  79. //        var latitude:CLLocationDegrees = userLocation.coordinate.latitude
  80. //        var longitude:CLLocationDegrees = userLocation.coordinate.longitude
  81.        
  82.         var latString : NSString = "-34.4232722"
  83.         var lngString : NSString = "150.8865837"
  84.        
  85.         var latitude = latString.doubleValue
  86.         var longitude = lngString.doubleValue
  87. //        var latString:String = "\(latitude)"
  88. //        var lngString:String = "\(longitude)"
  89.        
  90.         var latDelta:CLLocationDegrees = 0.03
  91.         var lonDelta:CLLocationDegrees = 0.03
  92.        
  93.         var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
  94.         var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
  95.        
  96.         var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
  97.        
  98.         mapView.setRegion(region, animated: false)
  99.        
  100.         // stop updating the location
  101.         manager.stopUpdatingLocation()
  102.        
  103.         self.lat = latString
  104.         self.lng = lngString
  105.        
  106.         // Get the deals from the deal model
  107.         self.deals = getDeals()
  108.  
  109.         // Add annotations to the map
  110.         var index:Int
  111.         for var index = 0; index < deals.count; ++index {
  112.            
  113.             var currentdeal = self.deals[index]
  114.             var lat = NSString(string: currentdeal.latitude.stringByTrimmingCharactersInSet(NSCharacterSet.punctuationCharacterSet()))
  115.             var latDouble:CLLocationDegrees = -lat.doubleValue
  116.             var long = NSString(string: currentdeal.longitude.stringByTrimmingCharactersInSet(NSCharacterSet.punctuationCharacterSet()))
  117.             var longDouble:CLLocationDegrees = long.doubleValue
  118.            
  119.             var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latDouble, longDouble)
  120.            
  121.             var annotation = MKPointAnnotation()
  122.            
  123.             annotation.coordinate = location
  124.             annotation.title = currentdeal.location
  125.             annotation.subtitle = "Deal Available"
  126.             self.mapView.addAnnotation(annotation)
  127.            
  128.         }
  129.     }
  130.    
  131.     func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
  132.        
  133.         if annotation is MKUserLocation {
  134.             //return nil so map view draws "blue dot" for standard user location
  135.             return nil
  136.         }
  137.        
  138.         var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier("pin")
  139.        
  140.         if pinView == nil {
  141.             pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pin")
  142.             pinView!.canShowCallout = true
  143.             pinView!.image = UIImage(named: "mappin")
  144.            
  145.             // Add image to left callout
  146. //            var mugIconView = UIImageView(image: UIImage(named: "mappin"))
  147. //            pinView!.leftCalloutAccessoryView = mugIconView
  148.            
  149.             // Add detail button to right callout
  150.             var calloutButton = UIButton.buttonWithType(.DetailDisclosure) as UIButton
  151.             pinView!.rightCalloutAccessoryView = calloutButton
  152.             calloutButton.addTarget(self, action: Selector("DetailView"), forControlEvents: UIControlEvents.TouchUpInside)
  153.         }
  154.         else {
  155.             pinView!.annotation = annotation
  156.         }
  157.        
  158.         return pinView
  159.     }
  160.    
  161.     func DetailView(){
  162.        
  163.         println("Button Pressed")
  164.     }
  165.    
  166.     func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
  167.         println(error)
  168.     }
  169.  
  170.     func getDeals() -> [Deal] {
  171.        
  172.         // Array of deal objects
  173.         var deals:[Deal] = [Deal]()
  174.         self.latArray = [String]()
  175.         // Get Json array of dictionaries
  176.         let jsonObjects:[NSDictionary] = self.getRemoteJsonFile()
  177.        
  178.         // Loop through each dictionary and assign values to our deal objs
  179.         var index:Int
  180.         for index = 0; index < jsonObjects.count; index++ {
  181.            
  182.             // Current JSON dict
  183.             let jsonDictionary:NSDictionary = jsonObjects[index]
  184.            
  185.             let restaurantDictionarys:[NSDictionary] = jsonDictionary["restaurants"] as [NSDictionary]
  186.            
  187.            
  188.             // Create a deal obj
  189.             var q:Deal = Deal()
  190.            
  191.             // Assign the values of each key value pair to the deal object
  192.             q.title = jsonDictionary["name"] as String
  193.             q.price = jsonDictionary["price_data"] as String
  194.             q.imageID = jsonDictionary["id"] as String
  195.             q.location = restaurantDictionarys[0]["name"] as String
  196.             q.latitude = restaurantDictionarys[0]["lat"] as String
  197.             self.latArray.append(q.latitude)
  198.             q.longitude = restaurantDictionarys[0]["lng"] as String
  199.             q.days = jsonDictionary["availability_day"] as String
  200.             q.time = jsonDictionary["availability_time"] as String
  201.            
  202.             // Add the question to the question array
  203.             deals.append(q)
  204.         }
  205.         println(self.latArray)
  206.         // Return list of question objects
  207.         return deals
  208.        
  209.     }
  210.    
  211.     func getRemoteJsonFile() -> [NSDictionary] {
  212.        
  213.         // Create a new URL
  214. //        let remoteUrl:NSURL? = NSURL(string: "http://staging.api.cheapeat.com.au/search?lat=\(self.lat)&lng=\(self.lng)")
  215.         let remoteUrl:NSURL? = NSURL(string: "http://staging.api.cheapeat.com.au/search?lat=-34.4232722&lng=150.8865837")
  216.         let urlString:String = "\(remoteUrl)"
  217.         println(urlString)
  218.        
  219.         // Check if it's nil
  220.         if let actualRemoteUrl = remoteUrl {
  221.            
  222.             // Try to get the data
  223.             let fileData:NSData? = NSData(contentsOfURL: actualRemoteUrl)
  224.            
  225.             // Check if it's nil
  226.             if let actualFileData = fileData {
  227.                
  228.                 // Parse out the dictionaries
  229.                 let arrayOfDictionaries:[NSDictionary]? = NSJSONSerialization.JSONObjectWithData(actualFileData, options: NSJSONReadingOptions.MutableContainers, error: nil) as [NSDictionary]?
  230.                
  231.                 if let actualArrayOfDictionaries = arrayOfDictionaries {
  232.                    
  233.                     // Successfully parsed out array of dictionaries
  234.                     return actualArrayOfDictionaries
  235.                 }
  236.             }
  237.            
  238.         }
  239.         return [NSDictionary]()
  240.     }
  241.  
  242. }
Advertisement
Add Comment
Please, Sign In to add comment