如何在Swift中调用Web服务并正确格式化响应?

时间:2014-06-10 23:01:27

标签: nsurlconnection swift

所以我正在对端点进行简单的NSURLConnection并尝试序列化我回来的JSON,但最后仍然得到一个空字典。这是我的代码......

import Cocoa
import Foundation


let endpoint = "http://api.ihackernews.com/page"

var url = NSURL(string: endpoint)
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: nil, startImmediately: false)


class Response : NSObject, NSURLConnectionDelegate {

    var data: NSMutableData = NSMutableData()
    var results: NSDictionary = NSDictionary()

    func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        // Recieved a new request, clear out the data object
        data = NSMutableData()
    }

    func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
        // Append the recieved chunk of data to our data object
        self.data.appendData(data)
    }

    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(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary



    }

}



var response = Response().results

正如您所看到的那样,我在最后检查了响应变量,并获得了#键/值对'从Swift编译器返回。

有什么想法吗?

0 个答案:

没有答案