HTTP Requests in Swift 3

前端 未结 3 1097
终归单人心
终归单人心 2021-02-14 05:17

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

3条回答
  •  悲&欢浪女
    2021-02-14 05:49

    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.

提交回复
热议问题