swift – 使用dataTask返回值的函数

swift – 使用dataTask返回值的函数,第1张

概述我不想检查我的url statusCode是否等于200,如果statusCode等于200,我创建了一个返回布尔函数的函数,我正在使用dataTask,但我不知道如何返回一个值: class func checkUrl(urlString: String) -> Bool{ let urlPath: String = urlString var url: NSURL = NSU 我不想检查我的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})

希望这会有所帮助.

总结

以上是内存溢出为你收集整理的swift – 使用dataTask返回值的函数全部内容,希望文章能够帮你解决swift – 使用dataTask返回值的函数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1051153.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存