我编写了以下两个使用 NSURLSession 的函数。
func getStringFromRequest(completionHandler:(success:Bool, data: NSData?) -> Void) {
let prefs = NSUserDefaults.standardUserDefaults()
var conn_timeout = prefs.stringForKey("conn_timeout")!
var IP = prefs.stringForKey("IP")!
var port = prefs.stringForKey("Port")!
prefs.synchronize()
var request = NSMutableURLRequest(URL: NSURL(string: "http://\(IP):\(port)/")!)
var response: NSURLResponse?
var error: NSError?
var jsonString = ["osname":"iOS","mobile_manufacturer" : "Apple","mobile_model" : "iPhone Simulator","osversion" : "8.4"] as Dictionary<String, String>
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(jsonString, options: nil, error: &error)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("gzip", forHTTPHeaderField: "Accept-encoding")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
if let unwrappedError = error {
print("error=\(unwrappedError)")
}
else {
if let unwrappedData = data {
completionHandler(success: true, data: unwrappedData)
return
}
}
completionHandler(success: false, data: nil)
}
task.resume()
}
func performPost() -> NSDictionary {
var result = NSDictionary()
getStringFromRequest { (success, data) -> Void in
if (success) {
if let unwrappedData = data {
if let responseString = NSString(data: unwrappedData, encoding: NSUTF8StringEncoding) {
println("------------------>>>>>>NSURLSession>>>>>>>-------------------------->\n: \(responseString)")
result = (NSJSONSerialization.JSONObjectWithData(unwrappedData, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary)!
}
}
}
else {
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Failed>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
}
}
}
我按如下方式调用performPost函数:
self.connectionHelper.performPost()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { ()->() in
println("self.connectionHelper.result>>>>>>========================================>>>>>>> : \(self.connectionHelper.result)!")
})
输出如下:
self.connectionHelper.result>>>>>>========================================>>>>>>> : {
}!
------------------>>>>>>NSURLSession>>>>>>>-------------------------->
查看performPost函数的输出后,我可以说首先执行pritln函数,但它的调用晚于performPost。
如何在performPost函数中先设置result的值,然后在performPost函数完成后打印它的值。
这可能吗?
最佳答案
不要调用dispatch_async来打印结果,而是将完成处理程序 block 传递给performPost方法,并在该完成处理程序 block 中打印结果。
关于json - 将 NSURLSession 响应返回到其调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32500995/