gpt4 book ai didi

swift - 如何使用 dispatch_async 调用 2 个不同的 api 并在 Swift 中更新 UI

转载 作者:搜寻专家 更新时间:2023-11-01 06:20:48 24 4
gpt4 key购买 nike

我正在尝试进行后台 api 调用并在它返回结果时更新 UI,我已经检查了 GCD 文档。
是不是下面的逻辑有问题?

    // get data from server
let priority = DISPATCH_QUEUE_PRIORITY_BACKGROUND
dispatch_async(dispatch_get_global_queue(priority, 0)) {
self.getUserData() // update self.data1 global variable
self.getCompanyData() // update self.data2 global variable

dispatch_async(dispatch_get_main_queue()) {
self.updateUI() //update UI using self.data1 and self.data2 global variable
}

}


func getUserData(){
... api1 call
... print("1")

}

func getCompanyData(){
... api2 call
... print("2")
}

func updateUI(){
... print("UI")
}

当它执行时,输出基本上是;界面
1
2


我想在 api 两个 api 调用完成后调用 updateUI 函数。


以下api调用函数之一;

let fullUrl = self.apiDomain + "/user_details/" + String(self.user_id)
let url:NSURL = NSURL(string: fullUrl)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print(error)
return
}

var apiCallResult: [String:AnyObject]?
let result = NSString(data: data!, encoding: NSUTF8StringEncoding)
do {
apiCallResult = try NSJSONSerialization.JSONObjectWithData(result!.dataUsingEncoding(NSUTF8StringEncoding)!, options: []) as? Dictionary<String, AnyObject>
} catch let error as NSError {
print(error.localizedDescription)
return
}

let aa = apiCallResult!["data"]! as! NSDictionary
print(aa)

}

task.resume()

最佳答案

您可以使用 dispatch groups .下面是等待同步任务的代码示例:

let group = dispatch_group_create()

dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in
print("Block1")
NSThread.sleepForTimeInterval(1.0)
print("Block1 End")
}

dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in
print("Block2")
NSThread.sleepForTimeInterval(1.0)
print("Block2 End")
}

dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in
print("Block3")
}

并且可以产生这样的输出:

Block1
Block2
Block1 End
Block2 End
Block3

如果使用dispatch groups等待多个异步任务,则需要使用dispatch_group_enter, dispatch_group_leavedispatch_group_wait。这是代码示例。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
let group = dispatch_group_create()

print("Block1")
dispatch_group_enter(group)
foo1.sendAsynchronousRequest() {
print("Block1 End")
dispatch_group_leave(group)
}

print("Block2")
dispatch_group_enter(group)
foo2.sendAsynchronousRequest() {
print("Block1 End")
dispatch_group_leave(group)
}

dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
print("Block3")
})
}

阅读此处了解更多详情 http://www.raywenderlich.com/79150/grand-central-dispatch-tutorial-swift-part-2

关于swift - 如何使用 dispatch_async 调用 2 个不同的 api 并在 Swift 中更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34635780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com