Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 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?

like image 386
Dicky Tsang Avatar asked Jun 03 '14 13:06

Dicky Tsang


People also ask

How do you make HTTP requests with URLSession in Swift?

Before we start, we need to define the URL of the remote image. import UIKit let url = URL(string: "https://bit.ly/2LMtByx")! The next step is creating a data task, an instance of the URLSessionDataTask class. A task is always tied to a URLSession instance.

How do I send a HTTP request?

An HTTP client sends an HTTP request to a server in the form of a request message which includes following format: A Request-line. Zero or more header (General|Request|Entity) fields followed by CRLF. An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields.

How do I send a swift structure in an HTTP request?

Swift Struct as Request Body You can also send Swift structure in HTTP Response Body. For example, instead of sending HTTP Request parameters as we did in the example above  userId=300&title=My urgent task&completed=false, we can create a Swift structure and set it as HTTP Response body.

How do I make a request to an API endpoint?

A URLRequest can be created with a URL, representing the API endpoint to make a HTTP request to. If your HTTP request is to an API that requires authentication, you can set the necessary HTTP request headers on the URLRequest. If you need to make a POST request, you can set the httpMethod and httpBody on the URLRequest.

How to set HTTP request header in HTTP request?

If your HTTP Request needs to contain specific HTTP Request Headers, then below is an example of how you can do it. var request = URLRequest(url: requestUrl) request.httpMethod = "POST" // Set HTTP Request Header request.setValue("application/json", forHTTPHeaderField: "Accept") You can set more than one header.

How to convert covert response data into Swift structure?

Covert Response Data into Swift Structure Once the HTTP Response arrives, we can then decode the JSON Payload into a Swift Struct. In the code example above we have already done that. To convert data object container JSON string we will use JSONDecoder().  For example:


2 Answers

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.

Using URLSession

Initialize a URL object and a 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 NSURLConnection

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 NSURLConnection:

let connection = NSURLConnection(request: request, delegate:nil, startImmediately: true) 

Just make sure to set your delegate to something other 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

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.

like image 196
Cezar Avatar answered Oct 10 '22 03:10

Cezar


Check Below Codes :

1. SynchonousRequest

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 +

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

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 +

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

    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 +

   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. Asynchonous POST Request

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 +

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. Asynchonous GET Request

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 +

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

Swift 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() 
like image 33
PREMKUMAR Avatar answered Oct 10 '22 03:10

PREMKUMAR