Skip to content

Instantly share code, notes, and snippets.

@cmoulton
Last active November 4, 2022 00:29
Show Gist options
  • Save cmoulton/149b03b5ea2f4c870a44526a02618a30 to your computer and use it in GitHub Desktop.
Save cmoulton/149b03b5ea2f4c870a44526a02618a30 to your computer and use it in GitHub Desktop.
URLSession Calls in Swift 3.0.1
func makeGetCall() {
// Set up the URL request
let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
guard let url = URL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on /todos/1")
print(error)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let todo = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject] else {
print("error trying to convert data to JSON")
return
}
// now we have the todo, let's just print it to prove we can access it
print("The todo is: " + todo.description)
// the todo object is a dictionary
// so we just access the title using the "title" key
// so check for a title and print it if we have one
guard let todoTitle = todo["title"] as? String else {
print("Could not get todo title from JSON")
return
}
print("The title is: " + todoTitle)
} catch {
print("error trying to convert data to JSON")
return
}
}
task.resume()
}
@johndpope
Copy link

johndpope commented Oct 20, 2016

thinking of throwing this inside a simple swift docker container as a hello world example.

docker pull swiftdocker/swift
docker run --privileged -i -t --name swiftfun swiftdocker/swift:latest /bin/bash

tried running on https://swiftlang.ng.bluemix.net/#/repl
but it throws

Error running code:
WARNING: Your kernel does not support swap limit capabilities, memory limited without swap.
/swiftfiles/doit.sh: line 51: 40 Trace/breakpoint trap timeout ${TIMEOUT} .build/debug/TempCode


import Foundation
func makeGetCall() {
  // Set up the URL request
  let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
  guard let url = URL(string: todoEndpoint) else {
    print("Error: cannot create URL")
    return
  }
  let urlRequest = URLRequest(url: url)

  // set up the session
  let config = URLSessionConfiguration.default
  let session = URLSession(configuration: config)

  // make the request
  let task = session.dataTask(with: urlRequest) {
    (data, response, error) in
    // check for any errors
    guard error == nil else {
      print("error calling GET on /todos/1")
      print(error)
      return
    }
    // make sure we got data
    guard let responseData = data else {
      print("Error: did not receive data")
      return
    }
    // parse the result as JSON, since that's what the API provides
    do {
      guard let todo = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject] else {
        print("error trying to convert data to JSON")
        return
      }
      // now we have the todo, let's just print it to prove we can access it
      print("The todo is: " + todo.description)

      // the todo object is a dictionary
      // so we just access the title using the "title" key
      // so check for a title and print it if we have one
      guard let todoTitle = todo["title"] as? String else {
        print("Could not get todo title from JSON")
        return
      }
      print("The title is: " + todoTitle)
    } catch  {
      print("error trying to convert data to JSON")
      return
    }
  }

  task.resume()
}

makeGetCall()

@cmoulton
Copy link
Author

Sorry, I haven't done any work with running Swift in docker containers.

@alextud
Copy link

alextud commented Nov 28, 2016

It did run in docker for me, but I needed to do some changes on JSONSerialization casting to [String: Any]

func makeGetCall() {
// Set up the URL request
let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
guard let url = URL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)

// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)

// make the request
let task = session.dataTask(with: urlRequest) {
    (data, response, error) in
    
    if let data = data {
        print(String(data: data, encoding: .utf8) ?? "NO DATA")
    }
    
    if let response = response {
        print(response)
    }
    
    // check for any errors
    guard error == nil else {
        print("error calling GET on /todos/1")
        print(error!)
        return
    }
    // make sure we got data
    guard let responseData = data else {
        print("Error: did not receive data")
        return
    }
    // parse the result as JSON, since that's what the API provides
    do {
        guard let todo = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any] else {
            print("error trying to convert data to JSON")
            return
        }
        // now we have the todo, let's just print it to prove we can access it
        print("The todo is: " + todo.description)
        
        // the todo object is a dictionary
        // so we just access the title using the "title" key
        // so check for a title and print it if we have one
        guard let todoTitle = todo["title"] as? String else {
            print("Could not get todo title from JSON")
            return
        }
        print("The title is: " + todoTitle)
    } catch  {
        print("failed to serialize data to JSON")
        return
    }
}

task.resume()

}

@iosdev27
Copy link

iosdev27 commented Mar 13, 2017

Hi,

Not sure what's going on but this code doesn't print anything on the console. Am I missing something? Thanks.

V

@yalegria
Copy link

Same here, I dont see anything on the console.

Copy link

ghost commented Mar 17, 2017

Same. No output.

@gregoriomelo
Copy link

If you're running in Playground, you might need to import PlaygroundSupport (assuming you're on Swift 3):

import PlaygroundSupport

and, at the end of your file add the following:

PlaygroundPage.current.needsIndefiniteExecution = true

@lkennon
Copy link

lkennon commented Feb 15, 2020

No output either. Not in Playground but Swift project (Xcode 9.4.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment