在Swift(iOS)中一个接一个地调用异步任务
对于iOS天气应用程序,尝试在swift中使用dispatch async逐个运行多个异步任务时遇到问题。我想要'update()'函数:
I'm having problems with trying to run several asynchronous tasks one by one using dispatch async in swift, for an iOS weather app. I want my 'update()' function to:
- 获取用户的位置(并将纬度和经度存储在类变量中)
- 当位置服务完成后,根据新填充的lat& amp;来调用weather API。 API调用(以及后续的XML解析)完成后,更新UI(iOS表视图)
(对我来说很容易,我是一名最近自学成才的编码员,所以我假设有更多经验的人可以指出各种错误!任何帮助都将受到大力赞赏。)
(Go easy on me, I'm a recently self-taught coder, so I'm assuming the more experienced of you out there will be able to point out various errors! Any help would be massively appreciated.)
var latitude: String = ""
var longitude: String = ""
var locationManager: CLLocationManager!
var forecastData: Weather = Weather() // the weather class has it's own asynchronous NSURLSession called retrieveForecast()
// which calls the Open Weather Map API and parses the XML
func refresh() {
// Here's where I don't know what I'm doing:
let group = dispatch_group_create()
dispatch_group_enter(group)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
self.getLocation()
dispatch_group_leave(group)
}
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
self.getWeather()
}
self.updateUI() // ...and I know that this is in totally the wrong place!
}
// function(s) to get phone's location:
func getLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestWhenInUseAuthorization()
locationManager.distanceFilter = 100.0
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.locationManager.stopUpdatingLocation()
manager.stopUpdatingLocation()
for item: AnyObject in locations {
if let location = item as? CLLocation {
if location.horizontalAccuracy < 1000 {
manager.stopUpdatingLocation()
self.latitude = String(location.coordinate.latitude)
self.longitude = String(location.coordinate.longitude)
}
}
}
}
// function to download and parse the weather data within forecastData object
func getWeather() {
let apiCall = "http://api.openweathermap.org/data/2.5/forecast?lat=" + self.latitude
+ "&lon=" + self.longitude + "&mode=xml&appid=" + self.openWeatherMapAPIKey
NSLog("getWeather called with api request: \(apiCall)")
self.forecastData.retrieveForecast(apiCall)
}
对于任何异步操作,最好有一个完成回调。
在你的情况下,如果你实现了 getLocation
和 getWeather
的回调,你将永远不需要 dispatch_groups
,你只需从 getLocation
的回调中调用 getWeather
,然后你只需从 getWeather
的回调中调用 refreshUI
。
For any asynchronous operation it is a good manner to have a finish callback.
In your case, if you have implemented callbacks for getLocation
and getWeather
you'll never need dispatch_groups
, you just call getWeather
from getLocation
's callback, and then you just call refreshUI
from getWeather
's callback.
var latitude: String = ""
var longitude: String = ""
var locationManager: CLLocationManager!
var forecastData: Weather = Weather() // the weather class has it's own asynchronous NSURLSession called retrieveForecast()
// which calls the Open Weather Map API and parses the XML
func refresh() {
self.getLocation()
}
// function(s) to get phone's location:
func getLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestWhenInUseAuthorization()
locationManager.distanceFilter = 100.0
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.locationManager.stopUpdatingLocation()
manager.stopUpdatingLocation()
for item: AnyObject in locations {
if let location = item as? CLLocation {
if location.horizontalAccuracy < 1000 {
manager.stopUpdatingLocation()
self.latitude = String(location.coordinate.latitude)
self.longitude = String(location.coordinate.longitude)
self.getWeather()
}
}
}
}
// function to download and parse the weather data within forecastData object
func getWeather() {
let apiCall = "http://api.openweathermap.org/data/2.5/forecast?lat=" + self.latitude
+ "&lon=" + self.longitude + "&mode=xml&appid=" + self.openWeatherMapAPIKey
NSLog("getWeather called with api request: \(apiCall)")
self.forecastData.retrieveForecast(apiCall)
// assuming that self.forecastData.retrieveForecast(apiCall) is completely synchronous, we can call updateUI below
self.updateUI()
}
这里我代码,演示如何正确使用 dispatch_group
:
Here is the code, demonstrating how dispatch_group
can be used right way:
func refetchOrdersAndChats(remoteNotificationData: [NSObject : AnyObject], completion: ((Bool)->())?) {
var overallSuccess: Bool = true
let refetchGroup = dispatch_group_create();
dispatch_group_enter(refetchGroup);
CPChatController.sharedInstance.updateChat(remoteNotificationData, completion: { success in
overallSuccess = success && overallSuccess
dispatch_group_leave(refetchGroup);
})
dispatch_group_enter(refetchGroup);
CPChatController.sharedInstance.fetchNewOrdersWithNotification(remoteNotificationData, completion: { success in
overallSuccess = success && overallSuccess
dispatch_group_leave(refetchGroup);
})
dispatch_group_notify(refetchGroup,dispatch_get_main_queue(), {
completion?(overallSuccess)
})
}