我想返回数据类型:NSDictionary。但主要代码是空的NSDictionary
我怎么解决这个问题?我在函数中使用了JSON方法。
func regionDataReturn(rid: Int) -> NSDictionary {
var jsonResult: NSDictionary = NSDictionary()
let urlPath: String = "MY_SERVER/test.php"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "POST"
var stringPost="test_id=\(tid)" // Key and Value
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request1.timeoutInterval = 60
request1.HTTPBody=data
request1.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
self.navigationItem.title = jsonResult["name"] as? String
NSLog("\(self.navigationItem.title)")
})
return jsonResult
}
答案 0 :(得分:0)
你不能这样做。
您正在调用异步函数来获取数据,您的方法将在获取数据之前返回。您有两种方法可以解决此问题:
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil
var error: NSErrorPointer = nil
var data : NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
var err : NSError
jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
self.navigationItem.title = jsonResult["name"] as? String
NSLog("\(self.navigationItem.title)")