【问题标题】:Swift 4.Decodable + alamofireSwift 4.Decodable + alamofire
【发布时间】:2018-07-08 19:15:01
【问题描述】:

我在解码JSON 时遇到问题。尝试获取日出和日落时间,但没有任何效果。 帮助

func getData(latitude: String,longtitude: String) {
    let url = URL(string: "https://api.sunrise-sunset.org/json?lat=\(latitude)&lng=\(longtitude)")
    Alamofire.request(url!).responseJSON { (response) in
        print(response)
        guard let data = response.data else { return }
        do {
            let st = try JSONDecoder().decode(results.self, from: data)
            print(st.sunrise)
        }
        catch {
            print("error")
        }
    }
}

【问题讨论】:

    标签: json swift alamofire decodable


    【解决方案1】:

    你需要的是一个像这样解码的根结构

    struct Root : Decodable {
       let status: String
       let results: results
    }
    
    struct results: Decodable {
        let sunrise : string 
        //other struc proporties as well in here 
    let astronomical_twilight_end: String
    }
    

    所以 你可以这样做

    let root = try JSONDecoder().decode(Root.self, from: data)
    

    让结果 = root.result

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      • 2018-10-21
      • 2017-11-17
      • 1970-01-01
      • 2019-03-19
      • 2017-11-27
      相关资源
      最近更新 更多