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's typo errors (no url variable in the call) in your code.
Anyway, in Swift 3 it's better to use the new URL struct and the URLSession class.
Also, XCPlayground is now PlaygroundSupport.
And no need to use NSString when String is available.
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let url = URL(string: "http://stackoverflow.com/")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if let data = data,
html = String(data: data, encoding: String.Encoding.utf8) {
print(html)
}
}
task.resume()
Note: this is for Xcode 8 beta 2. On beta 1 you would have to do shared()
instead of shared
. If you're on iOS don't forget to import UIKit
, but this code also works for OS X if you import Cocoa
instead.