我有这段代码:
let urls : String = Baseurl+"lat="+latitude+"&lon="+longitude+"&APPID="+apiKey
if let url = NSURL(string: urls) {
do {
let jsonResult = try NSString(contentsOfURL: url, usedEncoding: nil)
do {
if let jsonRes = try NSJSONSerialization.JSONObjectWithData(jsonResult, options: []) as? NSDictionary {
print(jsonRes)
}
} catch let error as NSError {
print(error.localizedDescription)
}
但是这行有一个错误:if let jsonRes = try...
。错误是:cannot convert value of type 'NSString' to expected argument type 'NSData'
。
当我打印jsonResult时,我得到了这个:
{
"coord":{
"lon":-0.13,
"lat":51.51
},
"weather":[
{
"id":501,
"main":"Rain",
"description":"moderate rain",
"icon":"10d"
}
],
"base":"stations",
"main":{
"temp":284.46,
"pressure":1023,
"humidity":76,
"temp_min":283.15,
"temp_max":285.15
},
"visibility":10000,
"wind":{
"speed":7.7,
"deg":220
},
"clouds":{
"all":75
},
"dt":1449755400,
"sys":{
"type":1,
"id":5093,
"message":0.0414,
"country":"GB",
"sunrise":1449734113,
"sunset":1449762690
},
"id":2643743,
"name":"London",
"cod":200
}
如何访问这些值?
答案 0 :(得分:3)
NSJSONSerialization.JSONObjectWithData()
需要NSData
个对象,而不是String
。
替换
let jsonResult = try NSString(contentsOfURL: url, usedEncoding: nil)
与
let jsonResult = NSData(contentsOfURL: url)
并删除try。
我还应该注意,这不是发出网络请求的最佳方式,您应该使用NSURLSession
发出异步请求:
NSURLSession().dataTaskWithURL(NSURL(string: urls)!) { (data, response, error) -> Void in
if let data = data {
do {
let dict = try NSJSONSerialization.JSONObjectWithData(data, options: [])
print(dict)
} catch {
print(error)
}
}
}.resume()