2016-05-12 2 views
0

Я работаю с быстрым 2.2 и создал приложение, которое отправляет местоположение на сервер mdm. Я объявил класс как subClass из NSObject и включил CLLOcationManagerDelegate. Но методы, подобные didUpdateLocations() и didUpdateToLocation(), не вызываются. Я не использую ни одну из кнопок или ничего в представлении, которое отправляет местоположение. Я хочу, чтобы приложение отправляло местоположение на сервер, когда приложение обновляет местоположение. Вот мой код.Как вызвать методы делегирования диспетчера CLLocation в iOS7 с помощью swift

class LocationProcessHandler: NSObject , CLLocationManagerDelegate{ 

    var location = CLLocationManager() 
    func startLocationUpdates() { 



     NSLog("It entered the start location updates method of the location process handler") 
    if (!(CLLocationManager.locationServicesEnabled()) || (CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Denied)) { 

     NSLog("It Entered to create the managed app feedback ") 
     let persist = Persistence() 

        let json: [NSObject : AnyObject] = [ 
      "IsLocationSettingsEnabled" : "\(0)",mdmiosagent_Constants.MESSAGETYPEKEY : mdmiosagent_Constants.LOCATIONMSGTYPEKEY,mdmiosagent_Constants.UDIDKEY : persist.getObject(mdmiosagent_Constants.UDIDKEY),"TimeStamp" : "\(self.toLocalTime())" 
     ] 
     let userDefaults : NSUserDefaults = NSUserDefaults.standardUserDefaults() 
     userDefaults.setObject(json, forKey: mdmiosagent_Constants.MANAGED_APP_FEEDBACK) 
     userDefaults.synchronize() 
     NSLog("The dict to be sent as managed app feedback is \(json)") 
     do { 
     let jsonData : NSData = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted) 
      let wrapper = HttpWrapper() 
      wrapper.silentPostData(serverurl: mdmiosagent_Constants.NATIVE_APP_SERVLET, urldata: jsonData) 
     } catch { 
      NSLog("json error") 
     } 

} 
    location.delegate = self 
    location.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 


      if #available(iOS 8.0, *) { 
       location.requestWhenInUseAuthorization() 
      } 
     location.delegate = self 
     location.startUpdatingLocation() 
     NSLog("Started to monitor the significant location Changes") 
    location.stopMonitoringSignificantLocationChanges() 
    location.startMonitoringSignificantLocationChanges() 

    } 

func location(manager: CLLocationManager!, 
        didChangeAuthorizationStatus status: CLAuthorizationStatus) { 
    var shouldIAllow = false 
    var locationStatus = String() 
    switch status { 
    case CLAuthorizationStatus.Restricted: 
     locationStatus = "Restricted Access to location" 
    case CLAuthorizationStatus.Denied: 
     locationStatus = "User denied access to location" 
    case CLAuthorizationStatus.NotDetermined: 
     locationStatus = "Status not determined" 
    default: 
     locationStatus = "Allowed to location Access" 
     shouldIAllow = true 
    } 
    NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil) 
    if (shouldIAllow == true) { 
     NSLog("Location to Allowed") 
     // Start location services 
     location.startUpdatingLocation() 
    } else { 
     NSLog("Denied access: \(locationStatus)") 
    } 
} 

func processMessage (dict : NSDictionary) { 
    let msgType : NSString = dict.objectForKey(mdmiosagent_Constants.MESSAGETYPEKEY) as! String 
    if (msgType.isEqual(mdmiosagent_Constants.MONITORREGIONKEY)) { 
     // self.startmonitoring(dict) 
    } 
} 

func stopLocationUpdates() { 
    location.stopMonitoringSignificantLocationChanges() 
    location.stopUpdatingLocation() 

} 
// this particular function is Used with two commands but not used as of now 
func startmonitoring (currentLocation : CLLocation) { 
    let latitude : Double = currentLocation.coordinate.latitude 
    let Longitude : Double = currentLocation.coordinate.longitude 
    let regionID = "GeoFenceTrack" 
    let region: CLCircularRegion = CLCircularRegion.init(center: CLLocationCoordinate2DMake(latitude, Longitude), radius: Double(mdmiosagent_Constants.LOCATIONRADIUS)! , identifier: regionID) 
    location.delegate = self 
    location.desiredAccuracy = kCLLocationAccuracyBest 
    location.stopMonitoringForRegion(region) 
} 

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    NSLog("Location Updated") 
    let persist = Persistence() 
    let currentLocation : CLLocation = locations[0] 
    let latitude : Double = currentLocation.coordinate.latitude 
    let Longitude : Double = currentLocation.coordinate.longitude 
    let regionID = "GeoFenceTrack" 
    let region : CLCircularRegion = CLCircularRegion.init(center: CLLocationCoordinate2DMake(latitude, Longitude), radius: Double(persist.getObject(mdmiosagent_Constants.LOCATIONRADIUS))!, identifier: regionID) 
    self.sendLocation(currentLocation) 
    location.desiredAccuracy = kCLLocationAccuracyHundredMeters 
    location.delegate = self 
    location.stopMonitoringForRegion(region) 
} 

func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) { 
    NSLog("Location Updated") 

    let latitude : Double = newLocation.coordinate.latitude 
    let Longitude : Double = newLocation.coordinate.longitude 

    let regionID = "GeoFenceTrack" 
    let region : CLCircularRegion = CLCircularRegion.init(center: CLLocationCoordinate2DMake(latitude, Longitude), radius: Double(mdmiosagent_Constants.LOCATIONRADIUS)!, identifier: regionID) 
    location.startMonitoringForRegion(region) 
    let currentLocation = newLocation 
    self.sendLocation(currentLocation) 
} 

func sendLocation (currentLocation : CLLocation) { 
    let latitude: String = "\(Int(currentLocation.coordinate.latitude))" 
    let longitude : String = "\(Int(currentLocation.coordinate.longitude))" 

    let json: [NSObject : AnyObject] = [ 
     mdmiosagent_Constants.MESSAGETYPEKEY : mdmiosagent_Constants.LOCATIONMSGTYPEKEY, 
     mdmiosagent_Constants.LATITUDEKEY : latitude, 
     mdmiosagent_Constants.LONGITUDEKEY : longitude, 
     mdmiosagent_Constants.UDIDKEY : defaults.UDID, 
     "TimeStamp" : "\(self.toLocalTime())", 
     "IsLocationSettingsEnabled" : "\(CLLocationManager.locationServicesEnabled())" 
    ] 

    let userDefaults : NSUserDefaults = NSUserDefaults.standardUserDefaults() 
    userDefaults.setObject(json, forKey: mdmiosagent_Constants.MANAGED_APP_FEEDBACK) 
    userDefaults.synchronize() 
    do { 
     let jsonData : NSData = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted) 
     let wrapper = HttpWrapper() 
     wrapper.silentPostData(serverurl: mdmiosagent_Constants.NATIVE_APP_SERVLET, urldata: jsonData) 
    } catch { 
     NSLog("json error") 
    } 
+0

Вы можете задать свой вопрос и эти два метода. Ваши два метода не работают в iOS7? Я знаю, что нет никаких устаревших функций между iOS7 и iOS8 в CLLocationManagerDelegate https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManagerDelegate_Protocol/ –

+0

Мне нужно использовать requestWhenInuseAuthorization() и requestAlwaysAuthorization() право называть методы делегата? Эти два метода устарели. –

+0

Вам не нужно вызывать эти две функции до iOS8, поэтому ваш вопрос заключается в том, когда вы вызываете эти функции, ваше приложение будет аварийно завершено? –

ответ

2

в прошивке 7 и выше вы можете использовать следующие методы

func locationManager(manager: CLLocationManager!,didUpdateLocations locations: [AnyObject]!){ 
    print("latitude:\(manager.location.coordinate.latitude)") 
    print("longitude:\(manager.location.coordinate.longitude)") 
} 


func locationManager(manager: CLLocationManager!,didFailWithError error: NSError!){ 
    print("error") 
} 

гарантированных однократный ваш класс подтверждает

import CoreLocation 

class ViewController: UIViewController , CLLocationManagerDelegate{ 

chcek как по вызову

self.locationManager = CLLocationManager() 
    let Device = UIDevice.currentDevice() 
private let iosVersion = Double(Device.systemVersion) ?? 0 
if iosVersion >= 8 { 
self.locationManager.requestWhenInUseAuthorization() 
} 
self.locationManager.delegate = self 
self.locationManager.startUpdatingLocation() 

обновления

добавить это и проверить, как только статус уже предоставлен или не

// authorization status 
func locationManager(manager: CLLocationManager!, 
    didChangeAuthorizationStatus status: CLAuthorizationStatus) { 
     var shouldIAllow = false 

     switch status { 
     case CLAuthorizationStatus.Restricted: 
      locationStatus = "Restricted Access to location" 
     case CLAuthorizationStatus.Denied: 
      locationStatus = "User denied access to location" 
     case CLAuthorizationStatus.NotDetermined: 
      locationStatus = "Status not determined" 
     default: 
      locationStatus = "Allowed to location Access" 
      shouldIAllow = true 
     } 
      NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil) 
     if (shouldIAllow == true) { 
      NSLog("Location to Allowed") 
      // Start location services 
      locationManager.startUpdatingLocation() 
     } else { 
      NSLog("Denied access: \(locationStatus)") 
     } 
} 
+0

Могу ли я использовать его как таковой без вызова requestWhenInuseAuthorization() и requestAlwaysAuthorization()? –

+0

Не является подклассом UIViewController, это то, что мешает вызовам методов? –

+0

chcek обновленный ответ братан –

Смежные вопросы