这是我来自服务器的 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);
?>
这就是我尝试从 swift 中获取 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).
刚接触 swift 和 http 请求,所以不完全确定这意味着什么。
最佳答案
您的应用崩溃的原因是 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
})
}
关于json - 快速解析 json 数组的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32802972/