【问题标题】:How parse JSON from 2 URLs properly?如何正确解析来自 2 个 URL 的 JSON?
【发布时间】:2017-11-20 12:30:45
【问题描述】:

我需要从 2 个不同的 URL 解析 JSON

let jsonUrlStr1 = "https://123"
let jsonUrlStr2 = "https://325"

guard let url1 = URL(string: jsonUrlStr1) else { return }
guard let url2 = URL(string: jsonUrlStr2) else { return }

我正在为第一个 url 运行会话:

    URLSession.shared.dataTask(with: url1) { (data, response, err) in

        if err != nil {
            print("Error:\(String(describing: err))")
        }

        guard let data = data else { return }

        do {

      let myData1 = try JSONDecoder().decode(SomeJsonModel1.self, from: data)

            //Some code

        } catch let jsonErr {
            print("Error:\(jsonErr)")
        }

        }.resume()//URLSession

然后,我正在为第二个 url 运行另一个会话,使用相同的方式:

URLSession.shared.dataTask(with: url2) { (data, response, err) in

    if err != nil {
        print("Error:\(String(describing: err))")
    }

    guard let data = data else { return }

    do {

  let myData2 = try JSONDecoder().decode(SomeJsonModel2.self, from: data)

        //Some code

    } catch let jsonErr {
        print("Error:\(jsonErr)")
    }

    }.resume()//URLSession

这段代码有效,我得到了结果。 但我认为应该有更正确的方法来解析 2 个 URL。 请告知如何正确执行。谢谢。

【问题讨论】:

    标签: ios json swift parsing


    【解决方案1】:

    您可以尝试像这样使用完成块

    func getDataFromJson(url: String, completion: @escaping (_ success: [String : Any]) -> Void) {
            let request = URLRequest(url: URL(string: url)!)
            let task = URLSession.shared.dataTask(with: request) { Data, response, error in
    
                guard let data = Data, error == nil else {  // check for fundamental networking error
    
                    print("error=\(String(describing: error))")
                    return
                }
    
                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {  // check for http errors
    
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print(response!)
                    return
    
                }
    
                let responseJSON  = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String : Any]
                completion(responseJSON)
            }
            task.resume()
        }
    

    并像这样调用方法:

        let jsonUrlStr1 = "https://123"
        let jsonUrlStr2 = "https://325"
    
        getDataFromJson(url: jsonUrlStr1, completion: { response in
           print("JSON response for url1 :: ",response) // once jsonUrlStr1 get it's response call next API 
    
           getDataFromJson(url: jsonUrlStr2, completion: { response in
               print("JSON response for url2 :: ",response)
           })
    
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-05
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多