0

I'm trying to get the JSON from a website and parse it before printing it. I've got a class called "JSONImport", which should handle a JSON Import from a server and print it. A second class should make the call to start the Import and print the content of the JSON.

The following code is what I have so far (I took it from another question Downloading and parsing json in swift)

So this is my "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?");
    }
}

Inside another class, I would like to print the JSON by:

JSONImport.startConnection();

Now I get an error, because swift wants me to add a parameter to the call, making it look like:

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

Does someone have an idea, what I should put in there as a parameter? I am confused, as i didn't declare one.

Thank you all in advance!

Kind regards, Manuel

Community
  • 1
  • 1
Manuel
  • 13
  • 5

1 Answers1

0

startConnection() is a instance method, so you need to instantiate an JSONImport to call it.

Only type methods can be used that way. So it's essentially asking for an instance of JSONImport.

Here is how you should do it

let importer = JSONImport()
importer.startConnection()

or by calling from the type method

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

You can read more about instance/type methods at this guide

Peba
  • 440
  • 4
  • 14