斯威夫特3 REST API斯威夫特3.不工作
问题描述:
遇到问题与REST API这里是我的代码:斯威夫特3 REST API斯威夫特3.不工作
func getData()
{
let urlString = "http://dataservice.accuweather.com/locations/v1/regions?apikey=QVU3TATgJEdRyojFze6zivdrmiln9XlA"
let config = URLSessionConfiguration.default // Session Configuration
let session = URLSession(configuration: config) // Load configuration into Session
let url = URL(string: urlString)!
let task = session.dataTask(with: url, completionHandler: {
(data, response, error) in
if error != nil {
print(error!.localizedDescription)
} else {
do {
print("in do block")
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
{
print("if condition is true")
//Implement your logic
print(json)
} else
{
print("Error in json serial")
}
} catch {
print("error in JSONSerialization")
}
}
})
task.resume()
}
执行后,我可以看到下面的打印语句:
在做阻止儿子 错误serial
这里找不出JSON序列化命令有什么问题。预期的响应是一个JSON数组。任何帮助,将不胜感激。 THX
答
更改 if let json = try JSONSerialization.jsonObject(with: data!, options:[]) as? [String: Any]
要
if let json = try JSONSerialization.jsonObject(with: data!, options:[]) as? [Any]
怎么一回事,因为你已经是JSON “jsonWithArrayRoot” 检查这个进一步的细节。 https://developer.apple.com/swift/blog/?id=37
尝试在尝试序列化之前打印'data'的值 –
'data'很好。转换为字符串并打印出来。可以看到我的json字符串。 – Sri
尝试将选项更改为'.mutableContainers',并看看下面的内容:http://stackoverflow.com/a/39520853/4656341 – damiancesar