gpt4 book ai didi

ios - Swift:同步 Web 服务调用

转载 作者:可可西里 更新时间:2023-11-01 02:15:24 30 4
gpt4 key购买 nike

在 Swift 中,我正在调用 Web 服务(Google Places)并成功获取 Google Place ID。

当我遍历 JSON 响应并获取 Google Place ID 时,我想调用另一个 Web 服务(Google Place Details)

使用下面的代码,我得到的响应是:

estPlace_ID_1
Return Number Is: Nothing
estPlace_ID
Return Number Is: Nothing
.....
Function Phone Number is: 867-5309
Function Phone Number is: 867-5309

似乎在 for result in results 循环完成之前函数 get Details 没有被执行。

如何更改代码,使其等到执行 getDetails 后再继续迭代?

class func getDetails(id: String) -> String {
<Setup the request>
let session = NSURLSession.sharedSession()

//Second Request
let task = session.dataTaskWithRequest(request) { data, response, error in
do {
//Parse Result
print("Function Phone Number is" + phoneNumber)
}
catch {
}
}
task.resume()

return phoneNumber
}

//First request
<Setup the request>
let task = session.dataTaskWithRequest(request) { data, response, error in
//a few checks with guard statements

do {
//Extract results from JSON response
results = <FROM_JSON>

for result in results {
estPlace_ID = result["value"]

print(estPlace_ID)
print("return number is" + getDetails(estPlace_ID))
}
catch {
}
}
task.resume()
}

最佳答案

可以通过调度信号量实现函数调用阻塞,直到异步调用的结果到达。模式是:

create_semaphore()
someAyncCall() {
signal_semaphore()
}
wait_for_semaphore()
rest_of_the_code()

在您的情况下,您可以按如下方式修改 getDetails 方法:

class func getDetails(id: String) -> String {
<Setup the request>
let session = NSURLSession.sharedSession()
let sem = dispatch_semaphore_create(0)

//Second Request
let task = session.dataTaskWithRequest(request) { data, response, error in
do {
//Parse Result
print("Function Phone Number is" + phoneNumber)

} catch {
}
// the task has completed, signal this
dispatch_semaphore_signal(sem)
}
task.resume()

// wait until the semaphore is signaled
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER)

// we won't get here until dispatch_semaphore_signal() is called
return phoneNumber
}

要记住的一件重要事情(感谢 Rob 指出这一点)是您需要在不同的队列上调用 getDetails,否则您会遇到死锁:

dispatch_async(dispatch_get_global_queue(0, 0) ){
for result in results {
let estPlace_ID = result["value"]

print(estPlace_ID)
print("return number is" + getDetails(estPlace_ID))
}
}

请注意,在上面的示例中,dispatch_semaphore_wait 的第二个参数是 DISPATCH_TIME_FOREVER,这意味着调用代码将无限期地等待异步调用完成。如果你想设置一些超时,你可以创建一个 dispatch_time_t 值并传递它:

// want to wait at most 30 seconds
let timeout = 30
let dispatchTimeout = dispatch_time(DISPATCH_TIME_NOW, timeout * Int64(NSEC_PER_SEC))
dispatch_semaphore_wait(sem, dispatchTimeout)

关于ios - Swift:同步 Web 服务调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39135279/

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