This article is translated from: How to make an HTTP request in Swift?
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 or do I just need to import default libraries? Or is it not possible to make an HTTP request based on native swift code?
#1st floor
reference resources: https://stackoom.com/question/1clh8/ How to make HTTP request in Swift
#2nd floor
You can use URL, URLRequest and URLSession or asurlconnection as you'd normally do in Objective-C. Note that for iOS 7.0 and later, URLSession is preferred.
Using URLSession using URLSession
Initialize a URL object and a URLSessionDataTask from URLSession. Initialize a URL object and URLSessionDataTask from URLSession. Then run the task with resume().
let url = URL(string: "http://www.stackoverflow.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()
Using asurlconnection using asurlconnection
First, initialize a URL and a URLRequest: first, initialize a URL and a URLRequest:
let url = URL(string: "http://www.stackoverflow.com")! var request = URLRequest(url: url) request.httpMethod = "POST"
Then, you can load the request asynchronously with:
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) {(response, data, error) in guard let data = data else { return } print(String(data: data, encoding: .utf8)!) }
Or you can initialize an asurlconnection: or, you can initialize an asurlconnection:
let connection = NSURLConnection(request: request, delegate:nil, startImmediately: true)
Just make sure to set your delegate to something else than nil and use the delegate methods to work with the response and data received.
For more detail, check the documentation for the NSURLConnectionDataDelegate protocol For more details, see About the NSURLConnectionDataDelegate protocol Of file.
Testing on an Xcode playground
If you want to try this code on a Xcode playground, add import PlaygroundSupport to your playground, as well as the following call:
PlaygroundPage.current.needsIndefiniteExecution = true
This will allow you to use asynchronous code in playgrounds.
#3rd floor
I am using this guy's wrapper with good results so far https://github.com/daltoniam/swiftHTTP . so far, I'm using this guy's wrappers. They work well https://github.com/daltoniam/swiftHTTP . No big leaky abstractions So far, so far, there is no big Leak abstraction
Example
do { let opt = try HTTP.GET("https://google.com") opt.start { response in if let err = response.error { print("error: \(err.localizedDescription)") return //also notify app of failure as needed } print("opt finished: \(response.description)") //print("data is: \(response.data)") access the response of the data with response.data } } catch let error { print("got an error creating the request: \(error)") }
#4th floor
var post:NSString = "api=myposts&userid=\(uid)&page_no=0&limit_no=10" NSLog("PostData: %@",post); var url1:NSURL = NSURL(string: url)! var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! var postLength:NSString = String( postData.length ) var request:NSMutableURLRequest = NSMutableURLRequest(URL: url1) request.HTTPMethod = "POST" request.HTTPBody = postData request.setValue(postLength, forHTTPHeaderField: "Content-Length") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") var reponseError: NSError? var response: NSURLResponse? var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError) if ( urlData != nil ) { let res = response as NSHTTPURLResponse!; NSLog("Response code: %ld", res.statusCode); if (res.statusCode >= 200 && res.statusCode < 300) { var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)! NSLog("Response ==> %@", responseData); var error: NSError? let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary let success:NSInteger = jsonData.valueForKey("error") as NSInteger //[jsonData[@"success"] integerValue]; NSLog("Success: %ld", success); if(success == 0) { NSLog("Login SUCCESS"); self.dataArr = jsonData.valueForKey("data") as NSMutableArray self.table.reloadData() } else { NSLog("Login failed1"); ZAActivityBar.showErrorWithStatus("error", forAction: "Action2") } } else { NSLog("Login failed2"); ZAActivityBar.showErrorWithStatus("error", forAction: "Action2") } } else { NSLog("Login failed3"); ZAActivityBar.showErrorWithStatus("error", forAction: "Action2") }
It will help you safely
#5th floor
I am calling the json on login button click
@IBAction func loginClicked(sender : AnyObject) { var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API. var session = NSURLSession.sharedSession() request.HTTPMethod = "POST" var err: NSError? request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters. request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") var task = session.dataTaskWithRequest(request, completionHandler: else { var success = json2["success"] as? Int println("Success: \(success)") } }) task.resume() }
Here, I have made a separate dictionary for the parameters.
var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"]as NSDictionary return params } // You can add your own sets of parameter here.
#6th floor
Check Below Codes: check the following codes:
1. SynchonousRequest 1. SynchonousRequest
Swift 1.2 swift 1.2
let urlPath: String = "YOUR_URL_HERE" var url: NSURL = NSURL(string: urlPath)! var request1: NSURLRequest = NSURLRequest(URL: url) var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)! var err: NSError println(response) var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary println("Synchronous\(jsonResult)")
Swift 2.0 + fast 2.0+
let urlPath: String = "YOUR_URL_HERE" let url: NSURL = NSURL(string: urlPath)! let request1: NSURLRequest = NSURLRequest(URL: url) let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil do{ let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response) print(response) do { if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary { print("Synchronous\(jsonResult)") } } catch let error as NSError { print(error.localizedDescription) } }catch let error as NSError { print(error.localizedDescription) }
2. AsynchonousRequest 2. AsynchonousRequest
Swift 1.2 swift 1.2
let urlPath: String = "YOUR_URL_HERE" var url: NSURL = NSURL(string: urlPath)! var request1: NSURLRequest = NSURLRequest(URL: url) let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in var err: NSError var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary println("Asynchronous\(jsonResult)") })
Swift 2.0 + fast 2.0+
let urlPath: String = "YOUR_URL_HERE" let url: NSURL = NSURL(string: urlPath)! let request1: NSURLRequest = NSURLRequest(URL: url) let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in do { if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { print("ASynchronous\(jsonResult)") } } catch let error as NSError { print(error.localizedDescription) } })
3. As usual URL connection
Swift 1.2 swift 1.2
var dataVal = NSMutableData() let urlPath: String = "YOUR URL HERE" var url: NSURL = NSURL(string: urlPath)! var request: NSURLRequest = NSURLRequest(URL: url) var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)! connection.start()
Then
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){ self.dataVal?.appendData(data) } func connectionDidFinishLoading(connection: NSURLConnection!) { var error: NSErrorPointer=nil var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary println(jsonResult) }
Swift 2.0 + fast 2.0+
var dataVal = NSMutableData() let urlPath: String = "YOUR URL HERE" var url: NSURL = NSURL(string: urlPath)! var request: NSURLRequest = NSURLRequest(URL: url) var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)! connection.start()
Then
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){ dataVal.appendData(data) } func connectionDidFinishLoading(connection: NSURLConnection!) { do { if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary { print(jsonResult) } } catch let error as NSError { print(error.localizedDescription) } }
4. Asynchronous POST request
Swift 1.2 swift 1.2
let urlPath: String = "YOUR URL HERE" var url: NSURL = NSURL(string: urlPath)! var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url) request1.HTTPMethod = "POST" var stringPost="deviceToken=123456" // Key and Value let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding) request1.timeoutInterval = 60 request1.HTTPBody=data request1.HTTPShouldHandleCookies=false let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in var err: NSError var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary println("AsSynchronous\(jsonResult)") })
Swift 2.0 + fast 2.0+
let urlPath: String = "YOUR URL HERE" let url: NSURL = NSURL(string: urlPath)! let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url) request1.HTTPMethod = "POST" let stringPost="deviceToken=123456" // Key and Value let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding) request1.timeoutInterval = 60 request1.HTTPBody=data request1.HTTPShouldHandleCookies=false let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in do { if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { print("ASynchronous\(jsonResult)") } } catch let error as NSError { print(error.localizedDescription) } })
5. Asynchronous GET request
Swift 1.2 swift 1.2
let urlPath: String = "YOUR URL HERE" var url: NSURL = NSURL(string: urlPath)! var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url) request1.HTTPMethod = "GET" request1.timeoutInterval = 60 let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in var err: NSError var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary println("AsSynchronous\(jsonResult)") })
Swift 2.0 + fast 2.0+
let urlPath: String = "YOUR URL HERE" let url: NSURL = NSURL(string: urlPath)! let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url) request1.HTTPMethod = "GET" let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in do { if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { print("ASynchronous\(jsonResult)") } } catch let error as NSError { print(error.localizedDescription) } })
6. Image(File) Upload 6. Image (file) upload
Swift 2.0 + fast 2.0+
let mainURL = "YOUR_URL_HERE" let url = NSURL(string: mainURL) let request = NSMutableURLRequest(URL: url!) let boundary = "78876565564454554547676" request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") request.HTTPMethod = "POST" // POST OR PUT What you want let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil) let imageData = UIImageJPEGRepresentation(UIImage(named: "Test.jpeg")!, 1) var body = NSMutableData() body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) // Append your parameters body.appendData("Content-Disposition: form-data; name=\"name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("PREMKUMAR\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("Content-Disposition: form-data; name=\"description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("IOS_DEVELOPER\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) // Append your Image/File Data var imageNameval = "HELLO.jpg" body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("Content-Disposition: form-data; name=\"profile_photo\"; filename=\"\(imageNameval)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(imageData!) body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) request.HTTPBody = body let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in if error != nil { //handle error } else { let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)! print("Response:\(outputString)") } } dataTask.resume()