ios - Swift 2 解析读取JSON

标签 ios json swift2

我是 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/

相关文章:

ios - UIView 子类未收到 NSNotificationCenter 通知

ios - 动画 TableView 单元格以向左滑动

ios - 删除所有以前的 UITableViewCell Swift 3/4 iOS

java - 将两个 JSON 数组的值合并为 JSONObject java

swift - Alamofire 、Swift 2.0、SwiftyJSON : Parse response body as JSON

Realm:如何在Realm中临时存储对象而不持久化它?

android - 此 iOS UI 元素及其 Android 替代元素的名称?

ios - 在 ARKit 中放置、拖动和删除 SCNNode

java - 使用 Java 有条件地访问同一级别的 JsonElements

objective-c - swift 2.1 : Property cannot be marked dynamic?