Swift Playground REST Request

Example of REST request in Swift Playground

You can run this example in Swift Playground using MacOS.

Replace YOURENDPOINT with the url of your REST Endpoint.


// Foundation is required for URLSession
import Foundation

// PlaygroundSupport: https://developer.apple.com/documentation/playgroundsupport
import PlaygroundSupport

let url = URL(string: "[YOUR_ENDPOINT]")!

// needsIndefiniteExecution is required for async code https://developer.apple.com/documentation/playgroundsupport/playgroundpage/1964501-needsindefiniteexecution
PlaygroundPage.current.needsIndefiniteExecution = true

// shared.dataTask saves the data in memory
//https://developer.apple.com/documentation/foundation/urlsession/1407613-datatask
let task = URLSession.shared.dataTask(with: url) {
    
    // @escaping closure
    // https://docs.swift.org/swift-book/LanguageGuide/Closures.html
    (data, response, error) in
    
    // guard is like if but exit if the check fails
    guard error == nil else {
        print(error!)
        return
    }
    
    guard let responseData = data else {
        print("Error: no data")
        return
    }
    
    guard let httpResponse = response as? HTTPURLResponse else {
        print("Error: Response Error")
        return
    }
    
    // we decode the json answer and we print it
    let content = String(decoding: data!, as: UTF8.self)
    print("Response data: \(content)")
        
    PlaygroundPage.current.finishExecution()
}
// start the task
task.resume()