IOS Swift 3为同步和异步请求创建URLSession扩展

时间:2016-11-17 16:26:46

标签: ios swift nsurlsession

大家好我即将在swift 3中为URLSession创建一个扩展来创建同步和异步请求。这是我的实现

extension URLSession {
    func sendSynchronousRequest(request: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {
        let semaphore = DispatchSemaphore(value: 0)

        let task = self.dataTask(with: request) { (data, response, error) in
            completionHandler(data,response,error)
            semaphore.signal()
        }
        task.resume()
        semaphore.wait(timeout: .distantFuture)
    }

    func sendAsynchronousRequest(request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
        let task = self.dataTask(with: request) { data, response, error in
            completionHandler(data, response, error)
        }
        task.resume()
        return task
    }
}

我有Xcode建议我将@escaping插入到该函数中。不知道实施是否正确

我也在此行enter image description here

发出警告

任何人都知道如何更正扩展程序?帮助非常感谢!谢谢!

1 个答案:

答案 0 :(得分:11)

我发现了这个实现,但在swift1 / 2中无法记住。这不是我自己的。但我在swift3中重写了它。我无法记住我在哪里找到它:/

func synchronousDataTaskWithURL(url: URL) -> (Data?, URLResponse?, Error?) {
    var data: Data?, response: URLResponse?, error: Error?

    let semaphore = DispatchSemaphore(value: 0)

    dataTask(with: url) {
        data = $0; response = $1; error = $2
        semaphore.signal()
        }.resume()

    semaphore.wait()

    return (data, response, error)
}