本文介绍了Swift:解析JSON字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析JSON数据.我可以做的是将JSON数据另存为NSData文件.然后,我可以将其读取为NSDictionary,并为相应的文本字段设置一些值.我不能做的就是将这些值从JSON直接放到相应的文本字段中.数据源是开放天气图".这对我来说并不重要.我只需要数据就可以进行JSON解析.无论如何,以下是我所拥有的.

I'm trying to parse JSON data. What I can do is to save JSON data as an NSData file. Then I can read it as NSDictionary and set some values to respective text fields. What I cannot do is to put those values from JSON directly to respective text fields. The source of the data is Open Weather Map. That's not really important for me. I just need data to practice JSON parsing. 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迫使我将self置于每个文本字段之前.我可以想象为什么.无论如何,结果,我的文本字段为空.该应用程序不会崩溃.我在做什么错了?

Xcode has forced me to put self before each text field. I can image why. Anyway, as a result, I have empty text fields. The application doesn't crash. What am I doing wrong?

谢谢.

推荐答案

@ J.Wang指出了正确的做法.问题是UI不在主线程上更新.正如文档所述,completionHandler将在委托队列上执行,因此我们必须与主队列一起分派它.顺便说一句,我也得到警告,该应用程序正在尝试在后台线程上修改自动布局...

@J.Wang has pointed out the right thing. The problem is UI is not updating on the main thread. As docs states the the completionHandler will be executed on the delegate queue so we have to dispatch it with the main queue. By the way i also got warning that this application is trying to modify autolayout on the background thread...

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

这篇关于Swift:解析JSON字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:26