In swift 3.0 for the GET method:
var request = URLRequest(url: URL(string: "Your URL")!) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error print("error=\(String(describing: error))") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(String(describing: response))") } let responseString = String(data: data, encoding: .utf8) print("responseString = \(String(describing: responseString))") } task.resume()
In swift 3.0 for the POST method:
var request = URLRequest(url: URL(string: "Your URL")!) request.httpMethod = "POST" let postString = "user_name=ABC" // Your parameter request.httpBody = postString.data(using: .utf8) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error print("error=\(String(describing: error))") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(String(describing: response))") } let responseString = String(data: data, encoding: .utf8) print("responseString = \(String(describing: responseString))") } task.resume()
source share