我正在尝试返回变量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
}
答案 0 :(得分:1)
在异步调用返回结果之前,您将返回{% for house_name in event_data.house_list|list %}
{% set home_def = salt['pillar.get']('homes:list:{}'.format(house_name)) %}
...
{% endfor %}
。您可以通过传递闭包并在Web服务返回结果时调用它来处理这种情况。对于该实现,方法如:
statusCode
您可以调用以下方法:
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()
}
}