NSURLConnection utilizando iOS Swift

NSURLConnection seguir este tutorial y conectarme a una API api usando Swift y NSURLConnection . Puedo ver que está llegando a la url, pero el connectionDidFinishLoading no parece disparar.

 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") 

En este punto, solo estoy tratando de ver los datos que se devuelven. Me gustaría conectarlo a un controlador de vista una vez que estoy seguro de que esto está funcionando. ¿Hay algún problema al hacerlo de esta manera y eso está causando un problema?

Verifique los códigos a continuación:

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=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=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. Como conexión de URL habitual

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

Entonces

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

Entonces

 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. Solicitud POST asincrónica

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. Solicitud GET asíncrona

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. Subida de imagen (archivo)

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

Una versión abreviada de tu código funcionó para mí,

 class Remote: NSObject { var data = NSMutableData() func connect(query:NSString) { var url = NSURL.URLWithString("http://www.google.com") var request = NSURLRequest(URL: url) var conn = NSURLConnection(request: request, delegate: self, startImmediately: true) } func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { println("didReceiveResponse") } func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) { self.data.appendData(conData) } func connectionDidFinishLoading(connection: NSURLConnection!) { println(self.data) } deinit { println("deiniting") } } 

Este es el código que utilicé en la clase de llamada,

 class ViewController: UIViewController { var remote = Remote() @IBAction func downloadTest(sender : UIButton) { remote.connect("/apis") } } 

No especificaste en tu pregunta dónde tenías este código,

 var remote = Remote() remote.connect("/apis") 

Si var es una variable local, la clase Remote se desasignará justo después de que finalice el método connect (query: NSString), pero antes de que los datos vuelvan. Como puede ver por mi código, generalmente implemento reinit (o dealloc hasta ahora) solo para asegurarme de que mis instancias se vayan. Debe agregar eso a su clase de Remote para ver si ese es su problema.

Swift 3.0

AsynchonousRequest

 let urlString = "http://heyhttp.org/me.json" var request = URLRequest(url: URL(string: urlString)!) let session = URLSession.shared session.dataTask(with: request) {data, response, error in if error != nil { print(error!.localizedDescription) return } do { let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary print("Synchronous\(jsonResult)") } catch { print(error.localizedDescription) } }.resume()