【发布时间】:2016-08-08 04:13:33
【问题描述】:
我正在从这样的 URL 中检索数据:
let url = NSURL(string: baseURL)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error == nil {
let swiftyJSON = JSON(data: data!)
let results = swiftyJSON[0]["name"]
print(results)
} else {
print("error")
}
}
对于上述,我得到这样的数据:
[
{
"_id":"123",
"_rev":"345",
"name":"hey"
},
{
"_id":"133",
"_rev":"33345",
"name":"hello"
}
]
我总是遇到错误块,我不知道为什么?
我将 JSON 粘贴到 chrome 控制台中并且能够执行 swiftyJSON[0].name。我想打印上述 json OBJECT 中的所有元素。
错误:
error Optional(Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified hostname could not be found." UserInfo={NSUnderlyingError=0x7f87514ab570 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_kCFStreamErrorCodeKey=8, _kCFStreamErrorDomainKey=12}}, NSErrorFailingURLStringKey=http://localhost:3000/idea, NSErrorFailingURLKey=http://localhost:3000/idea, _kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8, NSLocalizedDescription=A server with the specified hostname could not be found.})
请注意,localhost:3000 已开启。
【问题讨论】:
-
该错误与解析 Json 无关。这是关于连接到您的本地主机。确保设备配置到本地主机上的相同端口。
标签: json swift xcode swifty-json