dwyl / learn-apple-watch-development

:green_book: Learn how to build Native Apple Watch (+iPhone) apps from scratch!
55 stars 5 forks source link

How to make a HTTP-get request in swift 3.1 using URLSession #34

Open sohilpandya opened 7 years ago

sohilpandya commented 7 years ago

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.

// 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")!
let urlSession = URLSession.shared
let getRequest = URLRequest(url: url)

// 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()
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()
PlaygroundPage.current.needsIndefiniteExecution = true

If you now run the playground, you should see the following information in the console

Jon Snow // String
(
    "Kit Harington" // Array
)
(
    "Season 1", // Array
    "Season 2",
    "Season 3",
    "Season 4",
    "Season 5",
    "Season 6"
)