如何返回数据类型:Swift中的NSDictionary

时间:2015-01-09 04:18:49

标签: ios iphone json swift nsdictionary

我想返回数据类型: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
}

1 个答案:

答案 0 :(得分:0)

你不能这样做。

您正在调用异步函数来获取数据,您的方法将在获取数据之前返回。您有两种方法可以解决此问题:

  1. 使用通知,传递完成处理程序或out参数以将值传递回调用的方法
  2. 进行同步通话
  3. 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)")