How do I make an HTTP request in Swift?

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

    An example for a sample "GET" request is given below.

    let urlString = "YOUR_GET_URL"
    let yourURL = URL(string: urlstring)
    let dataTask = URLSession.shared.dataTask(with: yourURL) { (data, response, error) in
    do {
        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
        print("json --- \(json)")
        }catch let err {
        print("err---\(err.localizedDescription)")
        }
       }
    dataTask.resume()
    

提交回复
热议问题