ios - iOS Swift 读取 Json 失败

标签 ios json swift swift2

我写了这段代码:

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/

相关文章:

ios - 如何在 Storyboard预览中滚动 tableview 或 scrollview

objective-c - 在iOS上从二进制NSData减去字符串

ios - 与输入相比,谷歌地图显示不同的位置

javascript - 如何在 jhipster 中管理来自自定义 REST 的 .json 响应数据

javascript - 绘制 JSON 数据图表 - 直接来自 IBM Cloudant(bluemix no-sql)数据库的 Javascript?请帮助 N00b

swift - 如何快速在动态 TableView 中创建动态 tableView?

ios - Xcode 传递数据

ios - 如何处理 JSON 数据的多个链接?

swift - 单值元组作为 swift 中结构的最后一个成员

ios - 我将如何在选项卡栏按钮点击(快速)上创建幻灯片菜单