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()
}
}
答案 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/。 祝好运!