我写了这段代码:
func json()
{
let url = NSURL(string: "http://www.educaon.com.br/api/index.php/login?user=" + (username as String))!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) -> Void in
print ("Task Completed")
if let data = data
{
do
{
if let dict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
{
dispatch_async(dispatch_get_main_queue(), {
self.SenhaJs = dict["SENHA"] as! String
self.IDJs = dict["ID"]as! Int
print (self.SenhaJs) //Resultado Esta Nulo
})
}
} catch let error as NSError {
print(error.localizedDescription)
}
} else if let error = error {
print(error.localizedDescription)
}
}
task.resume()
}
但是在 NSURLSession.sharedSession()
调用之后,应用程序会直接转到 task.resume
并且不会读取 JSON。
有人可以帮我吗?
最佳答案
您的代码对于执行网络请求和读取 JSON 是正确的。
问题可能出在您的网址上。我尝试了不同的网址
let url = NSURL(string: "https://itunes.apple.com/search?term=philip+glass")!
并能够验证结果。
您使用的 URL 返回 JSON 数组而不是字典。因此,你必须改变
if let dict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
至
if let array: NSArray = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSArray
并将结果作为数组而不是字典处理。
关于ios - iOS Swift 读取 Json 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33226276/