gpt4 book ai didi

swift - 带有 dataTask 返回值的函数

转载 作者:搜寻专家 更新时间:2023-10-31 08:11:24 24 4
gpt4 key购买 nike

我不想检查我的 url statusCode 是否等于 200,我创建了一个函数,如果 statusCode 等于 200 则返回一个 bool 值,我正在使用 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

最佳答案

为了返回值,您应该使用 block 。尝试像这样声明您的函数:

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

希望这会有所帮助。

关于swift - 带有 dataTask 返回值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40014830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com