下载/解析后在swift中打印json

时间:2016-02-05 16:11:26

标签: json swift

我试图从网站获取JSON并在打印之前解析它。 我有一个名为" JSONImport"的类,应该从服务器处理JSON导入并打印它。 第二个类应该调用以启动导入并打印JSON的内容。

以下代码是我到目前为止(我从另一个问题Downloading and parsing json in swift

中获取的代码

所以这是我的" JSONImport.swift":

var data = NSMutableData();

func startConnection(){
    let urlPath: String = "http://echo.jsontest.com/key/value";
    let url: NSURL = NSURL(string: urlPath)!;
    let request: NSURLRequest = NSURLRequest(URL: url);
    let connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!;
    connection.start();
}

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
    self.data.appendData(data);
}

func connectionDidFinishLoading(connection: NSURLConnection!) {
    // throwing an error on the line below (can't figure out where the error message is)
    do{
     let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary;
        print(jsonResult);}
    catch {
        print("Something went wrong?");
    }
}

在另一个类中,我想通过以下方式打印JSON:

JSONImport.startConnection();

现在我收到一个错误,因为swift要我在调用中添加一个参数,使它看起来像:

JSONImport.startConnection(<#T##JSONImport#>);

有人有想法,我应该把它作为参数放在那里吗? 我很困惑,因为我没有宣布一个。

提前谢谢大家!

亲切的问候,曼努埃尔

1 个答案:

答案 0 :(得分:0)

startConnection()是一个实例方法,因此您需要实例化一个JSONImport来调用它。

只能使用类型方法。因此,它基本上要求JSONImport的实例。

这是你应该怎么做的

let importer = JSONImport()
importer.startConnection()

或通过类型方法调用

let importer = JSONImport()
JSONImport.startConnection(importer)

您可以在此guide

了解有关实例/类型方法的更多信息