我正在尝试按照本教程并使用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")
此时,我只是想查看返回的数据。我确定一旦可以正常运行,便想将其挂接到视图控制器中。这样做是否有问题,并导致问题?
当年话下