Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

swift - Downloading JSON with NSURLSession doesn't return any data

I am currently trying to download, parse and print JSON from an URL. So far I got to this point:

1) A class (JSONImport.swift), which handles my import:

    var data = NSMutableData();
        let url = NSURL(string:"http://headers.jsontest.com");
        var session = NSURLSession.sharedSession();
        var jsonError:NSError?;
        var response : NSURLResponse?;

        func startConnection(){

            let task:NSURLSessionDataTask = session.dataTaskWithURL(url!, completionHandler:apiHandler)
            task.resume();

            self.apiHandler(data,response: response,error: jsonError);

        }

        func apiHandler(data:NSData?, response:NSURLResponse?, error:NSError?)
        {
            do{
                let jsonData : NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary;
                print(jsonData);
            }
            catch{
                print("API error: (error)");
            }
        }

My problem is, that the data in

do{
            let jsonData : NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary;
            print(jsonData);
        }

remains empty. When I debug,the connection starts successfully, with the given url as a parameter. But my jsonData variable doesn't get printed. Instead the catch block throws the error, stating that there is no data in my variable:

API error: Error Domain=NSCocoaErrorDomain Code=3840 "No value."

Can someone please help me with this? What am I missing?

Thank you all very much in advance!

[Edited after switching from NSURL Connection to NSURLSession]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's an example on how to use NSURLSession with a very convenient "completion handler".

This function contains the network call and has the "completion handler" (a callback for when the data will be available):

func getDataFrom(urlString: String, completion: (data: NSData)->()) {
    if let url = NSURL(string: urlString) {
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url) { (data, response, error) in
            // print(response)
            if let data = data {
                completion(data: data)
            } else {
                print(error?.localizedDescription)
            }
        }
        task.resume()
    } else {
        // URL is invalid
    }
}

You can use it like this, inside a new function, with a "trailing closure":

func apiManager() {
    getDataFrom("http://headers.jsontest.com") { (data) in
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
            if let jsonDict = json as? NSDictionary {
                print(jsonDict)
            } else {
                // JSON data wasn't a dictionary
            }
        }
        catch let error as NSError {
            print("API error: (error.debugDescription)")
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...