Want to make an HTTP request in Swift? You can use URL, URLRequest and URLSession or NSURLConnection as you’d normally do in Objective-C. Note that for iOS 7.0 and later, URLSession is preferred. Initialize a URL object and a URLSessionDataTask from URLSession. Then run the task with resume()
.
1 2 3 4 5 6 7 8 9 |
let url = URL(string: "http://www.freewebmentor.com")! let task = URLSession.shared.dataTask(with: url) {(data, response, error) in guard let data = data else { return } print(String(data: data, encoding: .utf8)!) } task.resume() |
NSURLConnection
First, initialize a URL and a URLRequest
:
1 2 3 |
let url = URL(string: "http://www.freewebmentor.com")! var request = URLRequest(url: url) request.httpMethod = "POST" |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.