gpt4 book ai didi

ios - 使用 NSURLSession 发出同步请求

转载 作者:行者123 更新时间:2023-11-28 06:55:34 25 4
gpt4 key购买 nike

我在另一个线程中调用了一些函数:

dispatch_async(dispatch_get_global_queue(priority, 0)) {
self.someFunction()
}

然后在这个函数中我想做同步请求:

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let dataSemaphore = dispatch_semaphore_create(0)

let task = session.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("error calling GET")
print(error)
return
}
print("ASYNC")
})
task.resume()

dispatch_semaphore_wait(dataSemaphore, DISPATCH_TIME_FOREVER)

print("SYNC")

但是线程在这一行停止dispatch_semaphore_wait(dataSemaphore, DISPATCH_TIME_FOREVER)

最佳答案

你从来没有发出信号量,把它放在你的完成处理程序的末尾:

dispatch_semaphore_signal(dataSemaphore)

关于ios - 使用 NSURLSession 发出同步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33756471/

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