2015-09-26 131 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 
    }) 
}