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 bel
There are a couple problems with your code:
Info.plist
file to connect to HTTP sites.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