Make REST API call in Swift

前端 未结 15 1326
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 04:20

I\'m trying to use Swift to make a GET call to a REST API, and have tried to follow numerous tutorials, but can\'t figure it out. Either because I cannot figure out how to

15条回答
  •  离开以前
    2020-12-02 04:44

    Swift 3.0

    let request = NSMutableURLRequest(url: NSURL(string: "http://httpstat.us/200")! as URL)
    let session = URLSession.shared
    request.httpMethod = "GET"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    
    let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
          if error != nil {
              print("Error: \(String(describing: error))")
          } else {
              print("Response: \(String(describing: response))")
          }
     })
    
     task.resume()
    

提交回复
热议问题