使用iOS Swift的NSURLConnection

我正在尝试按照本教程并使用Swift和来连接到JSON api NSURLConnection。我可以看到它正在击中url,但connectionDidFinishLoading似乎没有触发。


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

此时,我只是想查看返回的数据。我确定一旦可以正常运行,便想将其挂接到视图控制器中。这样做是否有问题,并导致问题?


ITMISS
浏览 734回答 3
3回答

当年话下

检查以下代码:1. SynchronousRequest斯威夫特1.2&nbsp; &nbsp; let urlPath: String = "YOUR_URL_HERE"&nbsp; &nbsp; var url: NSURL = NSURL(string: urlPath)!&nbsp; &nbsp; var request1: NSURLRequest = NSURLRequest(URL: url)&nbsp; &nbsp; var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil&nbsp; &nbsp; var dataVal: NSData =&nbsp; NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!&nbsp; &nbsp; var err: NSError&nbsp; &nbsp; println(response)&nbsp; &nbsp; var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary&nbsp; &nbsp; println("Synchronous\(jsonResult)")迅捷2.0 +let urlPath: String = "YOUR_URL_HERE"&nbsp; &nbsp; let url: NSURL = NSURL(string: urlPath)!&nbsp; &nbsp; let request1: NSURLRequest = NSURLRequest(URL: url)&nbsp; &nbsp; let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil&nbsp; &nbsp; do{&nbsp; &nbsp; &nbsp; &nbsp; let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(response)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("Synchronous\(jsonResult)")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch let error as NSError {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(error.localizedDescription)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }catch let error as NSError&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print(error.localizedDescription)&nbsp; &nbsp; }2. AsynchonousRequest斯威夫特1.2let urlPath: String = "YOUR_URL_HERE"&nbsp; &nbsp; var url: NSURL = NSURL(string: urlPath)!&nbsp; &nbsp; var request1: NSURLRequest = NSURLRequest(URL: url)&nbsp; &nbsp; let queue:NSOperationQueue = NSOperationQueue()&nbsp; &nbsp; NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in&nbsp; &nbsp; &nbsp; &nbsp; var err: NSError&nbsp; &nbsp; &nbsp; &nbsp; var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary&nbsp; &nbsp; &nbsp; &nbsp; println("Asynchronous\(jsonResult)")&nbsp; &nbsp; &nbsp; &nbsp;})迅捷2.0 +let urlPath: String = "YOUR_URL_HERE"&nbsp; &nbsp; let url: NSURL = NSURL(string: urlPath)!&nbsp; &nbsp; let request1: NSURLRequest = NSURLRequest(URL: url)&nbsp; &nbsp; let queue:NSOperationQueue = NSOperationQueue()&nbsp; &nbsp; NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in&nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("ASynchronous\(jsonResult)")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } catch let error as NSError {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(error.localizedDescription)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })3.照常URL连接斯威夫特1.2&nbsp; &nbsp; var dataVal = NSMutableData()&nbsp; &nbsp; let urlPath: String = "YOUR URL HERE"&nbsp; &nbsp; var url: NSURL = NSURL(string: urlPath)!&nbsp; &nbsp; var request: NSURLRequest = NSURLRequest(URL: url)&nbsp; &nbsp; var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!&nbsp; &nbsp; connection.start()然后&nbsp;func connection(connection: NSURLConnection!, didReceiveData data: NSData!){&nbsp; &nbsp; self.dataVal?.appendData(data)}func connectionDidFinishLoading(connection: NSURLConnection!){&nbsp; &nbsp; var error: NSErrorPointer=nil&nbsp; &nbsp; var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary&nbsp; &nbsp; println(jsonResult)}迅捷2.0 +&nbsp; &nbsp;var dataVal = NSMutableData()&nbsp; &nbsp; let urlPath: String = "YOUR URL HERE"&nbsp; &nbsp; var url: NSURL = NSURL(string: urlPath)!&nbsp; &nbsp; var request: NSURLRequest = NSURLRequest(URL: url)&nbsp; &nbsp; var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!&nbsp; &nbsp; connection.start()然后func connection(connection: NSURLConnection!, didReceiveData data: NSData!){&nbsp; &nbsp; dataVal.appendData(data)}func connectionDidFinishLoading(connection: NSURLConnection!){&nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(jsonResult)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } catch let error as NSError {&nbsp; &nbsp; &nbsp; &nbsp; print(error.localizedDescription)&nbsp; &nbsp; }}4.异步POST请求斯威夫特1.2&nbsp; &nbsp; let urlPath: String = "YOUR URL HERE"&nbsp; &nbsp; var url: NSURL = NSURL(string: urlPath)!&nbsp; &nbsp; var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)&nbsp; &nbsp; request1.HTTPMethod = "POST"&nbsp; &nbsp; &nbsp;var stringPost="deviceToken=123456" // Key and Value&nbsp; &nbsp; let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)&nbsp; &nbsp; request1.timeoutInterval = 60&nbsp; &nbsp; request1.HTTPBody=data&nbsp; &nbsp; request1.HTTPShouldHandleCookies=false&nbsp; &nbsp; let queue:NSOperationQueue = NSOperationQueue()&nbsp; &nbsp; &nbsp;NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in&nbsp; &nbsp; &nbsp; &nbsp; var err: NSError&nbsp; &nbsp; &nbsp; &nbsp; var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary&nbsp; &nbsp; &nbsp; &nbsp; println("AsSynchronous\(jsonResult)")&nbsp; &nbsp; &nbsp; &nbsp; })迅捷2.0 +let urlPath: String = "YOUR URL HERE"&nbsp; &nbsp; let url: NSURL = NSURL(string: urlPath)!&nbsp; &nbsp; let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)&nbsp; &nbsp; request1.HTTPMethod = "POST"&nbsp; &nbsp; let stringPost="deviceToken=123456" // Key and Value&nbsp; &nbsp; let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)&nbsp; &nbsp; request1.timeoutInterval = 60&nbsp; &nbsp; request1.HTTPBody=data&nbsp; &nbsp; request1.HTTPShouldHandleCookies=false&nbsp; &nbsp; let queue:NSOperationQueue = NSOperationQueue()&nbsp; &nbsp; NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in&nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("ASynchronous\(jsonResult)")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } catch let error as NSError {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(error.localizedDescription)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })5.异步GET请求斯威夫特1.2&nbsp; &nbsp; let urlPath: String = "YOUR URL HERE"&nbsp; &nbsp; var url: NSURL = NSURL(string: urlPath)!&nbsp; &nbsp; var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)&nbsp; &nbsp; request1.HTTPMethod = "GET"&nbsp; &nbsp; request1.timeoutInterval = 60&nbsp; &nbsp; let queue:NSOperationQueue = NSOperationQueue()&nbsp; &nbsp; &nbsp;NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in&nbsp; &nbsp; &nbsp; &nbsp; var err: NSError&nbsp; &nbsp; &nbsp; &nbsp; var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary&nbsp; &nbsp; &nbsp; &nbsp; println("AsSynchronous\(jsonResult)")&nbsp; &nbsp; &nbsp; &nbsp; })迅捷2.0 +let urlPath: String = "YOUR URL HERE"&nbsp; &nbsp; let url: NSURL = NSURL(string: urlPath)!&nbsp; &nbsp; let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)&nbsp; &nbsp; request1.HTTPMethod = "GET"&nbsp; &nbsp; let queue:NSOperationQueue = NSOperationQueue()&nbsp; &nbsp; NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in&nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("ASynchronous\(jsonResult)")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } catch let error as NSError {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(error.localizedDescription)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })6.图片(文件)上传迅捷2.0 +&nbsp; let mainURL = "YOUR_URL_HERE"&nbsp; &nbsp; let url = NSURL(string: mainURL)&nbsp; &nbsp; let request = NSMutableURLRequest(URL: url!)&nbsp; &nbsp; let boundary = "78876565564454554547676"&nbsp; &nbsp; request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")&nbsp; &nbsp; request.HTTPMethod = "POST" // POST OR PUT What you want&nbsp; &nbsp; let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)&nbsp; &nbsp; let imageData = UIImageJPEGRepresentation(UIImage(named: "Test.jpeg")!, 1)&nbsp; &nbsp; var body = NSMutableData()&nbsp; &nbsp; body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)&nbsp; &nbsp; // Append your parameters&nbsp; &nbsp; body.appendData("Content-Disposition: form-data; name=\"name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)&nbsp; &nbsp; body.appendData("PREMKUMAR\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)&nbsp; &nbsp; body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)&nbsp; &nbsp; body.appendData("Content-Disposition: form-data; name=\"description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)&nbsp; &nbsp; body.appendData("IOS_DEVELOPER\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)&nbsp; &nbsp; body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)&nbsp; &nbsp; // Append your Image/File Data&nbsp; &nbsp; var imageNameval = "HELLO.jpg"&nbsp; &nbsp; body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)&nbsp; &nbsp; body.appendData("Content-Disposition: form-data; name=\"profile_photo\"; filename=\"\(imageNameval)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)&nbsp; &nbsp; body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)&nbsp; &nbsp; body.appendData(imageData!)&nbsp; &nbsp; body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)&nbsp; &nbsp; body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)&nbsp; &nbsp; request.HTTPBody = body&nbsp; &nbsp; let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in&nbsp; &nbsp; &nbsp; &nbsp; if error != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //handle error&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)!&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("Response:\(outputString)")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; dataTask.resume()7. GET,POST,Etc Swift 3.0及更高版本let request = NSMutableURLRequest(url: URL(string: "YOUR_URL_HERE" ,param: param))!,&nbsp; &nbsp; cachePolicy: .useProtocolCachePolicy,&nbsp; &nbsp; timeoutInterval:60)request.httpMethod = "POST" // POST ,GET, PUT What you want&nbsp;let session = URLSession.shared&nbsp; let dataTask = session.dataTask(with: request as URLRequest) {data,response,error indo {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("ASynchronous\(jsonResult)")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } catch let error as NSError {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(error.localizedDescription)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; dataTask.resume()
打开App,查看更多内容
随时随地看视频慕课网APP