gpt4 book ai didi

ios - 如何在 UI 中快速显示 JSON

转载 作者:行者123 更新时间:2023-11-28 11:05:29 26 4
gpt4 key购买 nike

我尝试在 iPhone 上调整我的 Android 应用程序,但是当我要求我的服务器获取 JSON 对象时,出现 fatal error :

fatal error: unexpectedly found nil while unwrapping an Optional value

我认为我的 Storyboard或其他东西中的文本字段初始化不正确,但我找不到我的错误。

print(jsonResult) 为我提供了良好的 JSON,但在出现 fatal error 之后。

import UIKit

class ViewController: UIViewController {



@IBOutlet weak var labelCategory: UILabel!
@IBOutlet weak var imageViewOneTrash: UIImageView!
@IBOutlet weak var textFieldCoordinate: UITextField!
@IBOutlet weak var textFieldAddress: UITextField!
@IBOutlet weak var buttonShare: UIButton!
@IBOutlet weak var buttonCoppy: UIButton!
@IBOutlet weak var buttonDelete: UIButton!
@IBOutlet weak var buttonMaps: UIButton!
@IBOutlet weak var addressTxtFld: UITextField!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

// 1
let urlAsString = "http://www.website.sample"
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()

//2
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
print(error!.localizedDescription)
}

// 3
do{
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? [String:AnyObject] {

print(jsonResult)
// 4
let jsonAddress: String! = jsonResult["trash_temp_address"] as! String

dispatch_async(dispatch_get_main_queue(), {
self.addressTxtFld.text = jsonAddress
})
}

}catch let error as NSError {
print(error.localizedDescription)
}

})
// 5
jsonQuery.resume()

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

print(jsonResult) 的结果是:

["result": <__NSArrayM 0x15d62770>(
{
"cat_name" = Mobilier;
"country_name" = France;
"town_name" = Toulon;
"town_postal_code" = 83200;
"trash_temp_address" = "278-338 Chemin du Jonquet";
"trash_temp_date_time" = "2016-05-22 17:49:14";
"trash_temp_fk_category" = 2;
"trash_temp_id" = 99;
"trash_temp_img" = "/pics/IMG_20160622_174846.jpg.png";
"trash_temp_latitude" = "43.1395197";
"trash_temp_longitude" = "5.9106404";
}
)
]

最佳答案

  • 根对象是一个带有一个键result的字典。
  • key result 的值是字典数组

这会获取键 trash_temp_address 的值

if let jsonRootObject = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject] { // mutable containers are not needed

print(jsonRootObject)
if let jsonResult = jsonRootObject["result"] as? [[String:String]],
jsonAddress = jsonResult[0]["trash_temp_address"] {
dispatch_async(dispatch_get_main_queue()) {
self.addressTxtFld.text = jsonAddress
}
}
...

关于ios - 如何在 UI 中快速显示 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37977024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com