Making HTTP requests is core functionality for modern languages and one of the first things many developers learn when acclimating to new environments. When it comes to Swift there are a fair amount of solutions to this problem both built into the language and by the community. Let’s take a look at some of the most popular ones.


We’ll be using NASA’s Astronomy Picture of the Day API as the JSON API that we are interacting with in all of these examples because space is the coolest thing ever.


Before moving on, make sure you have up to date versions of Swift 3 on your machine. If you use OSX, you can install Xcode from that link and have Swift available on the command line. If you use Linux, you can download it using the previous link as well. For Windows users, this might be helpful.


Swift in the Terminal

We are going to use Swift on the command line in all of the following examples. This doesn’t mean you can’t copy and paste any of this to Xcode, but Swift has an array of useful command line utilities that make testing the code in this tutorial easy.

Follow along by opening your terminal and navigating to the directory where you want this code to live. My directory is named SwiftHTTP which you will see in the examples in the rest of this post.

Enter the following to generate an executable command line project:



swift package init --type executable


This will also generate a Package.swift file for you. With this, we can add dependencies to use Swift Package Manager for installing third party libraries.


HTTP Requests with URLRequest


First up, we are going to use a built-in API called URLRequest. This method is pretty straightforward, and the code is much better in Swift 3 than in earlier versions of the language.


If you’re following along using the command line, open up main.swift in the Sources directory that was generated from the previous command, and enter the following code:


import Foundation

// Set the URL the request is being made to.
let request = URLRequest(url: NSURL(string: "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")! as URL)
do {
    // Perform the request
    var response: AutoreleasingUnsafeMutablePointer<URLResponse?>? = nil
    let data = try NSURLConnection.sendSynchronousRequest(request, returning: response)

    // Convert the data to JSON
    let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]

    if let json = jsonSerialized, let url = json["url"], let explanation = json["explanation"] {
        print(url)
        print(explanation)
    }
}


That’s all you need to do to make an HTTP request. Head back to your terminal and run the following command, keeping in mind that you might have to modify this to fit the name of your Swift project:


swift build && .build/debug/SwiftHTTP


Full Article: Read more