如何使用swift在iOS7中调用CLLocation Manager委托方法

时间:2016-05-12 07:35:34

标签: ios swift cllocationmanager

我正在使用swift 2.2并创建了一个将位置发送到mdm服务器的应用程序。我已将该类声明为NSObject的子类,并包含了CLLOcationManagerDelegate。但是像didUpdateLocations()和didUpdateToLocation()这样的方法并没有被调用。我没有使用发送位置的视图中的任何按钮或任何内容。我希望应用程序在应用程序更新位置时将位置发送到服务器。这是我的代码。

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")
    }

1 个答案:

答案 0 :(得分:2)

在iOS 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)")
        }
}