ios - 使用 NSURLSession 发出同步请求

标签 ios multithreading swift nsurlsession

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

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/

相关文章:

ios - 将数据从 Node 服务器发送回 iOS 设备(使用 Swift)

ios - 双问号,它是如何工作的?

ios - 如何处理 iPhone 6S Plus 的字体大小?

iphone - 如何将 .sqlite3/.sqlite 文件导入 ios 应用程序?

c - 如何在线程之间暂停执行?

ios - 对 `InterfaceController` 使用 `ComplicationController' 逻辑

ios - 使用核心动画在屏幕上移动 UIImage

c# - 将节点添加到 TreeView 会导致 Thread-Exception

java - 通过单击按钮启动和停止线程

ios - 以编程方式获取项目中的框架数组 - Xcode