swift – 使用dataTask返回值的函数

前端之家收集整理的这篇文章主要介绍了swift – 使用dataTask返回值的函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我不想检查我的url statusCode是否等于200,如果statusCode等于200,我创建了一个返回布尔函数函数,我正在使用dataTask,但我不知道如何返回一个值:
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中的返回值返回错误

Unexpected non-void return value in void function

为了返回值,你应该使用块.尝试声明你的功能如下:
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,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
})

希望这会有所帮助.

原文链接:https://www.f2er.com/swift/320142.html

猜你在找的Swift相关文章