简体   繁体   English

Alamofire responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)

[英]Alamofire responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)

I had some working code that was getting results from a MySQL DB on a remote web server.我有一些工作代码从远程 Web 服务器上的 MySQL 数据库获取结果。 It is no longer working and I keep getting the message responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) .它不再工作,我不断收到消息responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) Here is some code...这是一些代码...

    Alamofire.request(ADS_URL, method: .get).validate().responseJSON { response in
        print("Request: \(String(describing: response.request))")   // original url request
        print("Response: \(String(describing: response.response))") // http url response
        print("Result: \(response.result)")                         // response serialization result

        switch response.result {
        case .success(let value):
            let json = JSON(value)
            print ("JSON: \(json)")

            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                print("Data: \(utf8Text)") // original server data as UTF8 string
            }

        case .failure(let error):
            print("Error while querying database: \(String(describing: error))")
            return
        }
    }

I am also using SwiftyJSON.我也在使用 SwiftyJSON。 Here are the results of the code...这是代码的结果......

Request: Optional(http://doyouado.com/adscan/get_ads)

Response: Optional(<NSHTTPURLResponse: 0x17502f3a0> { URL: http://doyouado.com/adscan/get_ads } { status code: 200, headers {
    Connection = "keep-alive";
    "Content-Length" = 0;
    "Content-Type" = "text/html; charset=UTF-8";
    Date = "Mon, 18 Sep 2017 16:04:37 GMT";
    Server = "nginx/1.12.1";
    "Set-Cookie" = "ado_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%225019d90891c70c81df8ebc2fe754a68f%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A15%3A%22109.150.214.128%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A86%3A%22ADoBroadcaster%2F1.0+%28com.GaryFrank.ADoBroadcaster%3B+build%3A1%3B+iOS+10.3.3%29+Alamofire%2F4.5.0%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1505750677%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D3130ef6f5541e6f944da5a5a1292350bf203fa1b; expires=Mon, 18-Sep-2017 18:04:37 GMT; Max-Age=7200; path=/";
} })

Result: FAILURE  

Error: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)

I have tried using .response and .responseString , but I get no information returned.我尝试使用.response.responseString ,但没有返回任何信息。 I am completley stumped.我完全被难住了。 This was all working fine.这一切都很好。 Hopefully there is someone that can shed some light on this?希望有人可以对此有所了解?

Just simply change .responseJSON to .responseData .只需简单地将.responseJSON更改为.responseData

And after this parse data:在此解析数据之后:

let jsonDecoder = JSONDecoder() 
let parsedData = try jsonDecoder.decode(T.self, from: data)

and no error:并且没有错误:

(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)

对我有用的是将编码从 JSONEncoding.default 更改为 URLEncoding.default!

Updating from Alamofire 4 to 5 caused the issue in my case.在我的情况下,从 Alamofire 4 更新到 5 导致了这个问题。 By default, it seems that Alamofire 5 returns the error Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength for empty response body with status code 200 .默认情况下,似乎 Alamofire 5 返回错误Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength对于状态码为200空响应主体。 So adding 200 to the list of emptyResponseCodes resolved the issue for me:因此,将200添加到 emptyResponseCodes 列表中为我解决了这个问题:

request.responseData(emptyResponseCodes: [200, 204, 205]) { ... } // the default is [204, 205]

Commonly this error comes when your API is 'GET' type and you pass 'POST' type.通常,当您的 API 为“GET”类型并且您传递“POST”类型时会出现此错误。

The same problem I faced and my solution is I replace .post to .get and then this error removed.我遇到的同样问题和我的解决方案是将.post替换为.get ,然后删除此错误。

For AFNetworking 3.0 :- go given path,对于 AFNetworking 3.0 :- 转到给定的路径,

pods > Pods > AFNetworking > Serialization > AFURLResponseSerialization.m豆荚 > 豆荚 > AFNetworking > 序列化 > AFURLResponseSerialization.m

then replace line no 228 ( self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; )然后替换第 228 行( self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];

with

self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];

Because of your response in form of text/html but that is not mentioned in AFNetworking then we add it manually.由于您的回复是text/html形式,但 AFNetworking 中未提及,因此我们手动添加它。

Note:- I debugging this problem for Alamofire.注意:- 我为 Alamofire 调试了这个问题。

When server sends back no response, Alamofire shows this message in the .failure block if you are printing the error message.当服务器没有返回响应时,如果您打印错误消息,Alamofire 会在.failure块中显示此消息。 Technically it is not an error.从技术上讲,这不是错误。 Alamofire didn't show this message in its earlier versions, but since one of the recent updates it started showing it. Alamofire 在其早期版本中没有显示此消息,但自从最近的更新之一开始显示它。

As I said it is not really an error, but to me its a bug in Alamorfire.正如我所说,这并不是一个真正的错误,但对我来说它是 Alamofire 中的一个错误。 And it is very annoying and misleading to keep seeing this in your log when there is no error on your client or server side.当您的客户端或服务器端没有错误时,继续在您的日志中看到这一点是非常烦人和误导的。

Here is how I silent it:以下是我将其静音的方法:

if (response.data?.count)! > 0 {print(error)}

And I do it when there is no response from the server, which is the expected behaviour since server is not supposed to send response in some cases.当服务器没有响应时我会这样做,这是预期的行为,因为在某些情况下服务器不应该发送响应。

Alamofire.request(MY_URL, method: .get, parameters: ["blabla": blablabla])
        .validate(statusCode: 200..<300)
        .responseJSON {
            response in
            switch response.result {
            case .success(let value):
                self.processResponse(value)
            case .failure(let error):
                if (response.data?.count)! > 0 {print(error)}
            }
    }

So the error message doesn't shows when nothing is returned from the server.因此,当服务器未返回任何内容时,不会显示错误消息。 In my opinion this should be the default behaviour.在我看来,这应该是默认行为。

Though the question is quite old, I wanted to provide to others what I recently discovered.虽然这个问题已经很老了,但我想把我最近发现的东西提供给其他人。

Since the error message is very generic and it doesn't help much, check that the url format you are using is correct.由于错误消息非常笼统并且没有太大帮助,请检查您使用的 url 格式是否正确。 I've gotten this only to discover that the url format was incorrect.我得到这个只是为了发现 url 格式不正确。 Once fixed things started working fine.一旦修复,事情就开始正常工作了。

对我有用的是从 .responseData 更改为 .response

I,m using alamofire and was getting same error as above, quite new ios,used this website for parsing Json response, it worked for me:我,我正在使用 alamofire 并且遇到与上面相同的错误,相当新的 ios,使用这个网站来解析 Json 响应,它对我有用:

https://quicktype.io/ https://quicktype.io/

just paste your response and your model is ready for parsing, thanks to this website只需粘贴您的响应,您的模型就可以解析了,感谢这个网站

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Alamofire:responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) - Alamofire: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) responseSerializationFailed(原因:Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) - responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) 失败:responseSerializationFailed(原因:Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) - FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed - Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed Alamofire 响应序列化失败 - Alamofire responseSerializationFailed Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误域=NSCocoaErrorDomain 代码=3840 - Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 Alamofire-responseSerializationFailed - Alamofire - responseSerializationFailed Alamofire:失败响应序列化失败 - Alamofire: FAILURE responseSerializationFailed Alamofire POST 请求:responseSerializationFailed - Alamofire POST request: responseSerializationFailed 解析 JSON 时出现 AFError Alamofire 5 - AFError Alamofire 5 when parsing JSON
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM