我是 Swift 2.0 的新手,但我有 OOP 语言方面的经验。我试图通过 JSON API 在标签中仅显示城市名称。但我经常收到错误“EXC_BAD_INSTRUCTION”和“Unwrapping nil”错误。我认为问题可能出在 URL 中。因为我已经尝试使用另一个 API,radnomuser.me/api 并且我得到了没有错误的结果。有人可以引导我找到解决方案,因为我在互联网上得到了很多答案,而且所有答案都不一样。如果您不明白我的问题,请随时提问,因为我认为这是至关重要的部分。 谢谢!
@IBOutlet weak var viaSegueTextView: UITextView!{
var viaSegue = ""
override func viewDidLoad() {
super.viewDidLoad()
getWeatherData()
}
//////////////////////////////////////////////////////////////////////////
func getWeatherData {
let endpoint = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98")
let data = NSData(contentsOfURL: endpoint!)
do {
if let json: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
if let name = json["name"] as? String
{
viaSegueLabel.text = "\(name)"
}
}
}catch let error as NSError{
print("\(error)")
}
}
}
最佳答案
import Foundation
func getWeatherData() {
guard let endpoint = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98"),
let data = NSData(contentsOfURL: endpoint) else { return }
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
if let name = json["name"] as? String {
print(name) // London
}
}
} catch let error as NSError{
print("\(error)")
}
}
getWeatherData() // prints
// London
关于ios - Swift 2 解析读取JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35871832/