Make REST API call in Swift

前端 未结 15 1382
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 04:20

I\'m trying to use Swift to make a GET call to a REST API, and have tried to follow numerous tutorials, but can\'t figure it out. Either because I cannot figure out how to

15条回答
  •  甜味超标
    2020-12-02 04:52

    Swift 4 - GET request

    var request = URLRequest(url: URL(string: "http://example.com/api/v1/example")!)
    request.httpMethod = "GET"
    
    URLSession.shared.dataTask(with: request, completionHandler: { data, response, error -> Void in
        do {
            let jsonDecoder = JSONDecoder()
            let responseModel = try jsonDecoder.decode(CustomDtoClass.self, from: data!)
            print(responseModel)
        } catch {
            print("JSON Serialization error")
        }
    }).resume()
    

    Don't forget to configure App Transport Security Settings to add your domain to the exceptions and allow insecure http requests if you're hitting endpoints without using HTTPS.

    You can use a tool like http://www.json4swift.com/ to autogenerate your Codeable Mappings from your JSON responses.

提交回复
热议问题