Ever wondered how you can communicate with a 3rd party from your iPhone app? Using HTTP requests of course! In this short tutorial, we'll be creating our very first request to a 3rd party API all inside of a Playground. 😄
The idea behind the HTTP-get request is to fetch information from the Game of Thrones API.
let's start by creating a new Playground in XCode. http-request
add the URL from which you want to fetch information from
// here we are initializing the URL Struct with the path which we want to access from the API
let url = URL(string: "http://anapioficeandfire.com/api/characters/583")!
next, let's instantiate a shared URLSession which will provide us with an API to interact with 3rd parties (fetch/post data)
let urlSession = URLSession.shared
create the URLRequest which will be used for fetching the data
let getRequest = URLRequest(url: url)
create the task that you'd like to run with the completion handler and run the task
// we are going to call the `dataTask` method which will retrieve the content of a url based on a specific URL request object and calls the completionHandler.
// completion handler returns
// | data | URLResponse | error (if present) |
// | ---- | ---- | ---- |
// | data retruned by server | returned object from HTTP or HTTPS requests | Error object (either error or nil)
let task = urlSssion.dataTask(with: getRequest as URLRequest, completionHandler: { _, _, _ in })
// then call task.resume to fetch the results.
task.resume()
Lets update the completion handler so that it prints some data for us and to check if this works.
let task = urlSession.dataTask(with: getRequest as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
// the data is returned in JSON format and needs to be converted into something that swift can work with
// we are converting it into a dictionary of type [String: Any]
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json["name"]!)
print(json["playedBy"]!)
print(json["tvSeries"]!)
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
Finally, add this line to let this task run in playgrounds
Ever wondered how you can communicate with a 3rd party from your iPhone app? Using HTTP requests of course! In this short tutorial, we'll be creating our very first request to a 3rd party API all inside of a Playground. 😄
The idea behind the HTTP-get request is to fetch information from the Game of Thrones API.
let's start by creating a new Playground in XCode.
http-request
add the URL from which you want to fetch information from
If you now run the playground, you should see the following information in the console