小编典典

dataTask函数返回值

swift

我不想检查我的网址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返回错误:

void函数中非预期的非无效返回值


阅读 377

收藏
2020-07-07

共1个答案

小编典典

为了返回值,您应该使用块。尝试像这样声明您的功能:

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
})

希望这会有所帮助。

2020-07-07