使用NSURLSession下载JSON不会返回任何数据

使用NSURLSession下载JSON不会返回任何数据

本文介绍了使用NSURLSession下载JSON不会返回任何数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试从网址下载,解析和打印JSON。
到目前为止,我得到了这一点:



1)一个类(JSONImport.swift),它处理我的导入:

  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 {
让jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data !, options:NSJSONReadingOptions.MutableContainers)as! NSDictionary;
print(jsonData);
}
catch {
print(API error:\(error));
}
}

我的问题



中的数据

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

保持为空。
当我调试,连接成功启动,以给定的url作为参数。但我的jsonData变量不打印。相反catch块抛出错误,说明我的变量中没有数据:

  API错误:Error Domain = NSCocoaErrorDomain代码= 3840无值。 

有人可以帮我吗?
我缺少什么?



非常感谢大家!



从NSURL连接切换到NSURLSession]

解决方案

这里有一个如何使用NSURLSession与一个非常方便的完成处理程序 / p>

此函数包含网络调用并具有完成处理程序(当数据可用时的回调):

  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)
如果let data = data {
completion(data:data)
} else {
print(error?.localizedDescription)
}
}
task.resume
} else {
// URL无效
}
}

你可以这样使用它,在一个新的函数中,有一个尾随闭包:

  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数据不是字典
}
}
catch让错误为NSError {
print(API错误:\(error.debugDescription))
}
}
}


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]

解决方案

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)")
        }
    }
}

这篇关于使用NSURLSession下载JSON不会返回任何数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 21:09