NSURLSession返回包含错误访问代码的数据

时间:2015-05-29 16:58:21

标签: swift http asynchronous nsurlsession

由于某种原因,此函数返回数据变量的nil值,我无法理解为什么。我已经搜索了很多帖子,但似乎找不到区别。我已经使用了不同数据的请求,但如果我查看响应它们是相同的。它只能说明:

if let JSONData = responseString?.dataUsingEncoding(NSUTF8StringEncoding) {

如果因为responseString值从未设置过,那么

并且永远不会进入。将其更改为隐含的

if let JSONData = responseString!.dataUsingEncoding(NSUTF8StringEncoding) {

返回错误的访问代码。

func getData(url: String, dataToSend: String, username: String, password: String) {

    someVar = [MyObjectType]()

    let request = NSMutableURLRequest(URL: NSURL(string: "%URLTOUSE%")!)
    request.HTTPMethod = "POST"
    let postString = "%POSTDATAHERE%"

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        dump(responseString)
        if let JSONData = responseString?.dataUsingEncoding(NSUTF8StringEncoding) {
            if var jsonDict = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: nil) as? NSDictionary {
                if var jsonInfo = jsonDict["data"] as? NSDictionary {
                    if var jsonInfoSub = jsonInfo["data"] as? [NSDictionary] {
                        for report in jsonInfoSub {
                            self.someVar.append(MyObjectType(json: report))
                        }
                    }
                }
            }
        }
    }

    task.resume()
}

所有帮助表示赞赏!

编辑:其他信息

这是其他变量的转储输出

转储data会返回错误的访问代码

response: - <NSHTTPURLResponse: 0x7fbc5aca7120> { URL: ____ } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Length" = 428205;
    "Content-Type" = "text/html; charset=iso-8859-1";
    Date = "Fri, 29 May 2015 17:11:04 GMT";
    "Keep-Alive" = "timeout=3, max=100";
    P3P = "CP=\"NOI DEVa TAIa OUR BUS UNI STA\"";
    Server = Apache;
    "Set-Cookie" = "_____; expires=Sat, 28-May-2016 17:11:04 GMT; HttpOnly, _____=76b17d064b58c412d078b5430ca9367e; HttpOnly";
    "X-Powered-By" = PleskLin;
    "X-Robots-Tag" = "noindex, nofollow";
} } #0

错误返回:- nil

0 个答案:

没有答案