2015-09-26 80 views
0

JSON数组,这是从服务器我的PHP文件:解析圈穿过迅速

<?php 

    $results = Array(
     Array(
      "name"  => "William", 
      "location" => "UK", 
      "action" => "Post Update" 
     ), 
     Array(
      "name"  => "Sammy", 
      "location" => "US", 
      "action" => "posted news" 
     ) 
    ); 

    header("Content-Type: application/json"); 
    echo json_encode($results); 
?> 

这就是我如何努力,以JSON数组从迅速

let urlPath = "http://someurltophpserver" 
     let url = NSURL(string: urlPath) 
     let session = NSURLSession.sharedSession() 
     let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in 
      if ((error) != nil) { 
       println("Error") 
      } else { 
       let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary 
       // do something with the data 
      } 
     }) 
     task.resume() 

应用崩溃内取在此行中let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary错误:

Could not cast value of type '__NSArrayM' (0x8c9b58) to 'NSDictionary' (0x8c9d74). 

新来迅速和HTTP请求,所以不能完全小号这意味着什么。

回答

1

你的应用崩溃的原因是因为as!。你试图强制展开一个可选的,所以如果在运行时失败,应用程序将崩溃。

更改行这样的:

if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary 
{ 
    // Do stuff if jsonResult set with a value of type NSDictionary 
} 

这将阻止应用程序崩溃,但它的外观由JSON串行器返回的顶级对象将是一个NSArray不是你似乎是一个NSDictionary预计,这可能是为什么该应用程序实际上是崩溃。 你的代码对编译器说:“让jsonResult等于一个肯定会成为NSDictionary的值”。

此外,作为一方,我会建议最简单的方式下载一些数据是与NSData(contentsOfURL:url)。使用Grand Central Dispatch在后台队列中运行此操作,以避免阻塞主线程(UI)。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { 

    let data = NSData(contentsOfURL: url) 

    // Run any other code on the main queue. Especially any UIKit method. 

    NSOperationQueue.mainQueue().addOperationWithBlock({ 

     // Do stuff with data 
    }) 
}