How do I make an HTTP request in Swift?

前端 未结 20 1097
不知归路
不知归路 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 06:06

    Basic Swift 3+ Solution

    guard let url = URL(string: "http://www.stackoverflow.com") else { return }
    
    let task = URLSession.shared.dataTask(with: url) { data, response, error in
    
      guard let data = data, error == nil else { return }
    
      print(NSString(data: data, encoding: String.Encoding.utf8.rawValue))
    }
    
    task.resume()
    

提交回复
热议问题