Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP Requests in Swift 3

I am fairly new to Swift, and am trying to make an HTTP request. I tried many of the ideas in this Stack Overflow question, but all caused errors when run in a playground; I believe this is because they are all in Swift 1.0-2.0.

How can I make an HTTP request in Swift 3?

Update I tried the first solution presented in this answer and, after completing Xcode's suggested "Fix-its" I encountered four errors:

enter image description here

like image 847
owlswipe Avatar asked Jul 10 '16 14:07

owlswipe


People also ask

What is URLSession in Swift?

The URLSession class and related classes provide an API for downloading data from and uploading data to endpoints indicated by URLs. Your app can also use this API to perform background downloads when your app isn't running or, in iOS, while your app is suspended.

How do I create a network request in Swift?

Before Swift 5.5, in order to make a network request, we must use the closure-based URLSession 's dataTask(with:completionHandler:) method to trigger a request that runs asynchronously in the background. Once the network request is completed, the completion handler will give us back the result from the network request.

What steps would you follow to make a network request Swift?

Before we start, we need to define the URL of the remote image. import UIKit let url = URL(string: "https://bit.ly/2LMtByx")! The next step is creating a data task, an instance of the URLSessionDataTask class. A task is always tied to a URLSession instance.


1 Answers

There are a couple problems with your code:

  1. By default, your app cannot connect to insecure (i.e. HTTP) site. It's a feature called App Transport Security. You need to make an exception in your app's Info.plist file to connect to HTTP sites.
  2. This: dataTask(urlwith: ! as URL). What are you trying to unwrap with the exclamation mark (!)? What's the variable name?

A lot of class names have changed between Swift 2 and 3 so those answers you've found may not be applicable. Below is an example that connects to httpbin.org to get your IP address:

import PlaygroundSupport
import Foundation

let url = URL(string: "https://httpbin.org/ip")

let task = URLSession.shared.dataTask(with: url!) { data, response, error in
    guard error == nil else {
        print(error!)
        return
    }
    guard let data = data else {
        print("Data is empty")
        return
    }

    let json = try! JSONSerialization.jsonObject(with: data, options: [])
    print(json)
}

task.resume()
PlaygroundPage.current.needsIndefiniteExecution = true
like image 200
Code Different Avatar answered Oct 13 '22 09:10

Code Different