gpt4 book ai didi

ios - 从变量中的 NSHTTPURLResponse 返回 statusCode

转载 作者:行者123 更新时间:2023-11-29 01:25:44 25 4
gpt4 key购买 nike

我正在尝试返回变量 statusCode,该变量应该采用 NSHTTPURLResponse 的 statusCode 属性的值,但是即使我检查并看到数据已成功发布,我也得到零。它返回我初始化变量的 0...我该怎么做?谢谢。

var statusCode = 0

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) {
let request = NSMutableURLRequest(URL: NSURL(string: escapedUrl!)!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

if error != nil {
statusCode = 0
} else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
statusCode = httpResponse.statusCode
} else {
statusCode = 0
}
}
}
task.resume()
}
return statusCode

}

最佳答案

您在异步调用返回结果之前返回 statusCode。您可以通过传递一个闭包并在 Web 服务返回结果时调用它来处理这种情况。为此,实现如下方法:

func postData(escapedUrl : String?, onCompletion:(Int)->Void)
{
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue)
{
let request = NSMutableURLRequest(URL: NSURL(string: escapedUrl!)!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{
data, response, error in

var statusCode = 0

if error != nil
{
statusCode = 0
}
else if let httpResponse = response as? NSHTTPURLResponse
{
if httpResponse.statusCode == 200
{
statusCode = httpResponse.statusCode
}
else
{
statusCode = 0
}
}
// Passing back the result
onCompletion(statusCode);
}
task.resume()
}
}

您可以像这样调用该方法:

postData("yourURLString") { (statusCode) -> Void in
// Check status code here
}

关于ios - 从变量中的 NSHTTPURLResponse 返回 statusCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34044250/

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