如何等到locaiton经理代表在swift中调用?

时间:2016-09-12 07:23:04

标签: ios iphone swift cllocationmanager

我有一个通用函数genParam(),只要我调用此方法,我想返回当前userGPS位置以及其他参数。但在我的情况下genParam()在调用委托方法之前立即返回didUpdateLocations.Is那里在返回genParam()之前等待委托方法的任何方式。

class CommonApiParamGenerator: NSObject,CLLocationManagerDelegate {

var locationManager = CLLocationManager()
var userGPSLoc:String = ""

func genParam(locationName:String)->NSMutableDictionary{

    self.getUserLocation()
    let guid = NSUUID().UUIDString
    let userName = SingleTon.sharedInstance.getUserName()
    let gpsLoc = self.userGPSLoc
   let commonParam = NSMutableDictionary(objects: [guid,userName,gpsLoc], forKeys: ["guid","userName","gpsLoc"])
    return commonParam

}


func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    let userLocation:CLLocation = locations[0] as CLLocation
    self.userGPSLoc = "\(userLocation.coordinate.latitude),\(userLocation.coordinate.longitude)"
    print("receivedGPS \(self.userGPSLoc)")
    manager.stopUpdatingLocation()

}


 func getUserLocation()
{
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()

}
  }

1 个答案:

答案 0 :(得分:3)

首先遵循单一责任原则我建议您移动代码,将位置放在单独的类中:

class LocationManager: NSObject, CLLocationManagerDelegate {
    let manager = CLLocationManager()
    private var completion: ((CLLocation) -> Void)?

    override init() {
        super.init()

        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
    }

    func getLocation(completion: (CLLocation) -> Void) {
        self.completion = completion
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    {
        let userLocation = locations[0] as CLLocation
        manager.stopUpdatingLocation()
        self.completion?(userLocation)
    }
}

然后重构你的课程:

class CommonApiParamGenerator: NSObject {
    var userGPSLoc:String = ""
    var locationManager = LocationManager()

    func genParam(locationName:String, completion: (NSMutableDictionary) -> Void) {
        let guid = NSUUID().UUIDString
        let userName = SingleTon.sharedInstance.getUserName()

        locationManager.getLocation { location in
            let userGPSLoc = "\(location.coordinate.latitude),\(location.coordinate.longitude)"
            completion(NSMutableDictionary(objects: [guid,userName,userGPSLoc], forKeys: ["guid","userName","gpsLoc"]))
        }
    }
}

用法:

let generator = CommonApiParamGenerator()
generator.genParam(locationName) { params in
    ...
}

主要思想是使用回调进行异步操作。

如果你不喜欢回调,或者有很多嵌套回调(回调地狱),你可以使用PromiseKit:http://promisekit.org/。 祝好运!