ios - How do I make an HTTP request in Swift?

ID : 6049

viewed : 158

Tags : iosobjective-cswiftiphonensurlsessionios





Top 5 Answer for ios - How do I make an HTTP request in Swift?

vote vote

98

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.

vote vote

85

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() 
vote vote

80

Another option is the Alamofire lib that offers Chainable Request / Response methods.

https://github.com/Alamofire/Alamofire

Making a Request

import Alamofire  Alamofire.request(.GET, "http://httpbin.org/get") 

Response Handling

Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])          .response { request, response, data, error in               print(request)               print(response)               print(error)           } 
vote vote

70

Swift 4 and above : Data Request using URLSession API

   //create the url with NSURL    let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! //change the url     //create the session object    let session = URLSession.shared     //now create the URLRequest object using the url object    let request = URLRequest(url: url)     //create dataTask using the session object to send data to the server    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in         guard error == nil else {            return        }         guard let data = data else {            return        }        do {          //create json object from data          if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {             print(json)          }       } catch let error {         print(error.localizedDescription)       }    })     task.resume() 

Swift 4 and above, Decodable and Result enum

//APPError enum which shows all possible errors enum APPError: Error {     case networkError(Error)     case dataNotFound     case jsonParsingError(Error)     case invalidStatusCode(Int) }  //Result enum to show success or failure enum Result<T> {     case success(T)     case failure(APPError) }  //dataRequest which sends request to given URL and convert to Decodable Object func dataRequest<T: Decodable>(with url: String, objectType: T.Type, completion: @escaping (Result<T>) -> Void) {      //create the url with NSURL     let dataURL = URL(string: url)! //change the url      //create the session object     let session = URLSession.shared      //now create the URLRequest object using the url object     let request = URLRequest(url: dataURL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)      //create dataTask using the session object to send data to the server     let task = session.dataTask(with: request, completionHandler: { data, response, error in          guard error == nil else {             completion(Result.failure(AppError.networkError(error!)))             return         }          guard let data = data else {             completion(Result.failure(APPError.dataNotFound))             return         }          do {             //create decodable object from data             let decodedObject = try JSONDecoder().decode(objectType.self, from: data)             completion(Result.success(decodedObject))         } catch let error {             completion(Result.failure(APPError.jsonParsingError(error as! DecodingError)))         }     })      task.resume() } 

example:

//if we want to fetch todo from placeholder API, then we define the ToDo struct and call dataRequest and pass "https://jsonplaceholder.typicode.com/todos/1" string url.

struct ToDo: Decodable {     let id: Int     let userId: Int     let title: String     let completed: Bool  }  dataRequest(with: "https://jsonplaceholder.typicode.com/todos/1", objectType: ToDo.self) { (result: Result) in     switch result {     case .success(let object):         print(object)     case .failure(let error):         print(error)     } } 

//this prints the result:

ToDo(id: 1, userId: 1, title: "delectus aut autem", completed: false) 
vote vote

54

Basic Swift 3+ Solution

guard let url = URL(string: "http://www.stackoverflow.com") else { return }  let task = URLSession.shared.dataTask(with: url) { data, response, error in    guard let data = data, error == nil else { return }    print(NSString(data: data, encoding: String.Encoding.utf8.rawValue)) }  task.resume() 

Top 3 video Explaining ios - How do I make an HTTP request in Swift?







Related QUESTION?