Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sohilpandya opened this issue May 4, 2017 · 0 comments
Open

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

sohilpandya opened this issue May 4, 2017 · 0 comments
Assignees

Comments

@sohilpandya
Copy link
Member

sohilpandya commented May 4, 2017

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

screen shot 2017-05-04 at 18 12 31

  • 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
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"
)
@sohilpandya sohilpandya self-assigned this May 4, 2017
@sohilpandya sohilpandya changed the title [WIP] How to make a HTTP-get request in swift 3.1 using URLSession How to make a HTTP-get request in swift 3.1 using URLSession May 5, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants