简体   繁体   English

Swift:解析JSON字典值

[英]Swift: Parsing JSON Dictionary Values

I'm trying to parse JSON data. 我正在尝试解析JSON数据。 What I can do is to save JSON data as an NSData file. 我能做的是将JSON数据保存为NSData文件。 Then I can read it as NSDictionary and set some values to respective text fields. 然后我可以将其作为NSDictionary读取并为相应的文本字段设置一些值。 What I cannot do is to put those values from JSON directly to respective text fields. 我不能做的是将JSON中的值直接放到相应的文本字段中。 The source of the data is Open Weather Map. 数据来源是开放天气图。 That's not really important for me. 这对我来说并不重要。 I just need data to practice JSON parsing. 我只需要数据来练习JSON解析。 Anyway, the following is what I have. 无论如何,以下就是我所拥有的。

@IBOutlet weak var coordField1: UITextField!
@IBOutlet weak var countryField1: UITextField!
@IBOutlet weak var ideeField1: UITextField!
@IBOutlet weak var nameField1: UITextField!
@IBOutlet weak var cntField1: UITextField!
@IBOutlet weak var codField1: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    enum JSONError: String, ErrorType {
        case NoData = "ERROR: no data"
        case ConversionFailed = "ERROR: conversion from JSON failed"
    }

    let urlPath = "http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=fb1b5dcb756e9a52c49ee6377a02d879"
    guard let endpoint = NSURL(string: urlPath) else { print("Error creating endpoint");return }
    let request = NSMutableURLRequest(URL:endpoint)
    NSURLSession.sharedSession().dataTaskWithRequest(request) { (data,response,error) -> Void in
        do {
            guard let dat = data else { throw JSONError.NoData }
            guard let jsonDict = try NSJSONSerialization.JSONObjectWithData(dat,options:[]) as? NSDictionary else { throw JSONError.ConversionFailed }
            //print(json)

            if let items1 = jsonDict["city"] as? NSDictionary {
                if let a = items1["coord"] {
                    if let lat = a["lat"] as? NSNumber {
                        print("\(lat.stringValue)") // It prints "55.75222"
                        self.coordField1.text = "lat: " + lat.stringValue as String + " "
                    }
                    if let lon = a["lon"] as? NSNumber {
                        print("\(lon.stringValue)") // √
                        self.coordField1.text = self.coordField1.text! + "lon: " + lon.stringValue as String
                    }
                }
            }

            let jdata:NSData = NSKeyedArchiver.archivedDataWithRootObject(jsonDict)
            jdata.writeToFile(self.filePath1(), atomically:true) // saving JSON as an NSData file

        } catch let error as JSONError {
            print(error.rawValue)
        } catch {
            print(error)
        }
        }.resume()
    }       
}

Xcode has forced me to put self before each text field. Xcode迫使我在每个文本字段之前放置自己。 I can image why. 我可以想象为什么。 Anyway, as a result, I have empty text fields. 无论如何,因此,我有空文本字段。 The application doesn't crash. 应用程序不会崩溃。 What am I doing wrong? 我究竟做错了什么?

Thanks. 谢谢。

@J.Wang has pointed out the right thing. @ J.Wang指出了正确的事情。 The problem is UI is not updating on the main thread. 问题是UI没有在主线程上更新。 As docs states the the completionHandler will be executed on the delegate queue so we have to dispatch it with the main queue. 正如文档所述,将在委托队列上执行completionHandler因此我们必须使用主队列进行调度。 By the way i also got warning that this application is trying to modify autolayout on the background thread... 顺便说一句,我也警告说这个应用程序试图在后台线程上修改autolayout ...

dispatch_async(dispatch_get_main_queue(), { () -> Void in
   self.coordField1.text = "lat: " + lat.stringValue as String + " "
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM