LoginSignup
2
1

More than 5 years have passed since last update.

Swift JSON from Web

Last updated at Posted at 2018-05-10

Way 1

func fetchData2() {
    let jsonUrlString = "https://....."
    URLSession.shared.dataTask(with: URL(string: jsonUrlString)! ) { (data, _, error) in

      if error != nil {
        print(error)
      }

      if let data = data {

        do {
          if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
            let response = json["response"] as? [String: Any]
            let location = response!["location"] as? [[String: Any]]

            for dic in location! {
              print("\(dic["prefecture"]) \(dic["city"])")
            }
          }

        } catch let error as NSError {
          print(error.debugDescription)
        }
      }
    }.resume()
  }

Way 2

func jsonParser(urlString: String, completionHandler: @escaping (_ data: NSDictionary) -> Void) -> Void
{
    let urlPath = urlString
    guard let endpoint = URL(string: urlPath) else {
        print("Error creating endpoint")
        return
    }

    URLSession.shared.dataTask(with: endpoint) { (data, response, error) in
        do {
            guard let data = data else {
                throw JSONError.NoData

            }
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else {
                throw JSONError.ConversionFailed
            }
            completionHandler(json)
        } catch let error as JSONError {
            print(error.rawValue)

        } catch let error as NSError {
            print(error.debugDescription)
        }
        }.resume()

}

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1