John Ramos John Ramos - 1 year ago 1347
Swift Question

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

Answer Source

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 to get your IP address:

import PlaygroundSupport
import UIKit

let url = URL(string: "")

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

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

PlaygroundPage.current.needsIndefiniteExecution = true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download