ios - 使用 Alamofire 在 Swift 中下载和解析 json

标签 ios json swift alamofire

抱歉,我对此很陌生,它们可能是我头脑中显而易见的东西,但我收到以下带有此代码的错误消息:

“ fatal error :在展开可选值时意外发现 nil。”

   var jsonReceived = Alamofire.request(.GET, getJsonURL).responseJSON {
        (request, response, jsonData, error) in
        if jsonData == nil {
            println(error)
        } else {
            println(jsonData)
            var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
            println(jsonResult)
        }
    }

最佳答案

为了简单起见,我将 Alamofire.request 代码放入 viewDidLoad() 中。你可以把它放在任何你想要的地方。

override func viewDidLoad() {
    Alamofire.request(.GET, getJsonURL).responseJSON {
            (request, response, jsonData, error) in
            if error != nil {
                println(error)
            } else if let json = jsonData as? [String:AnyObject] {
                println(json)

                // call a function with the new data. 
                self.processNewData(json)

                // or you could just use the json object here
                if let str = json["foo"] as? String {
                    self.myButton.setTitle(str, forState: .Normal)
                }
            } else {
                println("Failed to cast JSON to [String:AnyObject]")
            }
        }
}

func processNewData(json: [String:AnyObject]){
    // do whatever you want here with the parsed JSON
    if let str = json["bar"] as? String {
        myLabel.text = str
    }
}

关于ios - 使用 Alamofire 在 Swift 中下载和解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28228701/

相关文章:

c# - 使用 FromBody 在 WebAPI 中建模的对象的 JSON 数组

java - 如何配置 Jersey 客户端使用服务器期望的相同 json 格式?

swift - 将一个数字分解为一组单独的数字

ios - 如何将 UILabel 添加到 UICollectionView Controller

ios - Swift 3 - viewdidload 中的函数未完全执行

ios - Swift:如何无延迟地刷新 tableview (UIRefreshControl)

ios - 从 xib 转到 UIViewController

android - Flutter 应用程序中的 Bottomnavigationbar 项目图标

java - 帮助处理 JSON 错误和 google 翻译 api

快速用户界面 | VStack 不会在 ForEach 循环内部工作