Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLConnection Using iOS Swift

I am trying to follow this tutorial and connect to a JSON api using Swift and NSURLConnection. I can see that it is hitting the url but the connectionDidFinishLoading does not seem to fire.

import UIKit  class Remote: NSObject {      var host = "http://localhost:3000"     var query = String()     var data: NSMutableData = NSMutableData()      func connect(query:NSString) {         self.query = query         var url = self.document()         var conn = NSURLConnection(request: url, delegate: self, startImmediately: true)     }      func endpoint() -> NSURL {         var query = self.host + self.query         return NSURL(string: query)     }      func document() -> NSURLRequest {         return NSURLRequest( URL: self.endpoint() )     }      func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {         // Recieved a new request, clear out the data object         self.data = NSMutableData()     }      func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {         // Append the recieved chunk of data to our data object         self.data.appendData(conData)     }      func connectionDidFinishLoading(connection: NSURLConnection!) {         // Request complete, self.data should now hold the resulting info         // Convert the retrieved data in to an object through JSON deserialization         var err: NSError         var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(self.data, options:    NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary          println(jsonResult.count)     }   }   // Excecute the code  var remote = Remote() remote.connect("/apis") 

At this point I am just trying to see the data that is returned. I would like to hook it into a view controller once I am sure this is working. Is there something wrong with doing it this way and that is causing an issue?

like image 430
Ross Nelson Avatar asked Jun 12 '14 04:06

Ross Nelson


People also ask

What is NSURLConnection in Swift?

An NSURLConnection object lets you load the contents of a URL by providing a URL request object. The interface for NSURLConnection is sparse, providing only the controls to start and cancel asynchronous loads of a URL request. You perform most of your configuration on the URL request object itself. Note.

What is the difference between NSURLSession and NSURLConnection?

NSURLSession also provides nicer interfaces for requesting data using blocks, in that it allows you to combine them with delegate methods for doing custom authentication handling, redirect handling, etc., whereas with NSURLConnection, if you suddenly realized you needed to do those things, you had to refactor your code ...

What is URL session in Swift?

URLSession is one class of the URLSession API. There are a handful of types you need to become familiar with to perform an HTTP request in Swift. A URLSession instance is the manager or coordinator of the requests your application performs. A request is referred to as a task, an instance of the URLSessionTask .


1 Answers

Check Below Codes :

1. SynchronousRequest

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. Asynchronous 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. Asynchronous 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() 

7. GET,POST,Etc Swift 3.0 +

let request = NSMutableURLRequest(url: URL(string: "YOUR_URL_HERE" ,param: param))!,     cachePolicy: .useProtocolCachePolicy,     timeoutInterval:60) request.httpMethod = "POST" // POST ,GET, PUT What you want   let session = URLSession.shared      let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in  do {             if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {                 print("ASynchronous\(jsonResult)")             }         } catch let error as NSError {             print(error.localizedDescription)         }      }     dataTask.resume() 
like image 160
PREMKUMAR Avatar answered Sep 21 '22 09:09

PREMKUMAR