带有 dataTask 返回值的函数

function with dataTask returning a value

我不想检查我的 url statusCode 是否等于 200,我创建了一个函数 return 如果 statusCode 等于 200,我使用布尔值,我正在使用 dataTask,但是我不知道如何 return 一个值:

class func checkUrl(urlString: String) -> Bool{

    let urlPath: String = urlString
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(url: url as URL)
    var response: URLResponse?

    let session = Foundation.URLSession.shared


    var task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }

        if let data = data{
            print("data =\(data)")
        }
        if let response = response {
            print("url = \(response.url!)")
            print("response = \(response)")
            let httpResponse = response as! HTTPURLResponse
            print("response code = \(httpResponse.statusCode)")

            if httpResponse.statusCode == 200{
                return true
            } else {
                return false
            }
        }
    })
    task.resume()
}

if else 中的 return 是 return 错误:

Unexpected non-void return value in void function

您正在 return 从 Void 函数中获取一个值,该函数是 dataTask(_:, _:)

completionHandler 闭包

关于您的代码,有问题:您不能 return 该值,因为它是在不同的线程上执行的,它是一个异步操作。请查看此线程:Returning data from async call in Swift function

为了 return 值你应该使用块。尝试像这样声明您的函数:

class func checkUrl(urlString: String, finished: ((isSuccess: Bool)->Void) {

    let urlPath: String = urlString
    var url: NSURL = NSURL(string: urlPath)!
    var request: NSURLRequest = NSURLRequest(url: url as URL)
    var response: URLResponse?

    let session = Foundation.URLSession.shared


    var task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }

        if let data = data{
            print("data =\(data)")
        }
        if let response = response {
            print("url = \(response.url!)")
            print("response = \(response)")
            let httpResponse = response as! HTTPURLResponse
            print("response code = \(httpResponse.statusCode)")

            if httpResponse.statusCode == 200{
                finished(isSuccess: true)                
            } else {
                finished(isSuccess: false) 
            }
        }
    })
    task.resume()
}

然后这样称呼它:

checkUrl("http://myBestURL.com", finished { isSuccess in
// Handle logic after return here
})

希望这会有所帮助。

如果您想保留原来的 return 模式,请考虑 semaphore

func checkUrl(urlString: String) -> Bool {
    if let url = URL(string: fileUrl) {
        var result: Bool!

        let semaphore = DispatchSemaphore(value: 0)  //1. create a counting semaphore

        let session = URLSession.shared
        session.dataTask(with: url, completionHandler: { (data, response, error) in
            result = true  //or false in case
            semaphore.signal()  //3. count it up
        }).resume()

        semaphore.wait()  //2. wait for finished counting

        return result
    }

    return false
}

Swift4,适合我的情况 尝试在 dataTask 中添加 guard let data = data else { return },例如:

URLSession.shared.dataTask(with: request) { (data, response, error) in
    guard let data = data else { return }
    print("get some data")
}.resume()