首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用iOS Swift的NSURLConnection

使用iOS Swift的NSURLConnection
EN

Stack Overflow用户
提问于 2014-06-12 12:18:25
回答 2查看 105.4K关注 0票数 60

我正在尝试使用Swift和NSURLConnection跟踪this tutorial并连接到JSON api。我可以看到它正在命中url,但connectionDidFinishLoading似乎没有触发。

代码语言:javascript
复制
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

回答 2

Stack Overflow用户

发布于 2014-06-12 13:45:07

你的代码的一个简化版本对我来说是有效的,

代码语言:javascript
复制
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")
    }
}

这是我在调用类中使用的代码,

代码语言:javascript
复制
class ViewController: UIViewController {

    var remote = Remote()


    @IBAction func downloadTest(sender : UIButton) {
        remote.connect("/apis")
    }

}

你没有在你的问题中具体说明你在哪里有这个代码,

代码语言:javascript
复制
var remote = Remote()
remote.connect("/apis")

如果var是一个局部变量,那么在connect(query:NSString)方法完成之后,但在数据返回之前,远程类将被释放。正如您从我的代码中看到的,我通常会实现reinit (或dealloc到目前为止),以确保我的实例何时消失。您应该将它添加到您的远程类中,看看这是否是您的问题。

票数 3
EN

Stack Overflow用户

发布于 2016-12-05 15:56:25

Swift 3.0

AsynchonousRequest

代码语言:javascript
复制
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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24176362

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档