How do I make an HTTP request in Swift?

前端 未结 20 1069
不知归路
不知归路 2020-11-22 05:10

I read The Programming Language Swift by Apple in iBooks, but cannot figure out how to make an HTTP request (something like cURL) in Swift. Do I need to import Obj-C classes

20条回答
  •  既然无缘
    2020-11-22 05:54

    Here's a very simple Swift 4 example in a playground:

    import UIKit
    // run asynchronously in a playground
    import PlaygroundSupport
    PlaygroundPage.current.needsIndefiniteExecution = true
    
    // create a url
    let url = URL(string: "http://www.stackoverflow.com")
    
    // create a data task
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil {
            print("there's a problem")
        }
        print(String(data: data!, encoding: String.Encoding.utf8) ?? "")
    }
    
    //running the task w/ resume
    task.resume()
    

提交回复
热议问题