可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Alamofire.request(.GET, "url").authenticate(user: "", password: "").responseJSON() { (request, response, json, error) in println(error) println(json) }
This is my request with Alamofire, for a certain request it sometime works, but sometimes i get:
Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x78e74b80 {NSDebugDescription=Invalid value around character 0.})
Why am i getting this error sometimes?
回答1:
i also faced same issue i tried responseString instead of responseJSON and it worked .i guess this is bug in alamofire with using it with django .
回答2:
I got same error while uploading image in multipart form in Alamofire as i was using
multipartFormData.appendBodyPart(data: image1Data, name: "file")
i fixed by replacing by
multipartFormData.appendBodyPart(data: image1Data, name: "file", fileName: "myImage.png", mimeType: "image/png")
Hope this help someone.
回答3:
May this Help YOu
Alamofire.request(.GET, "YOUR_URL") .validate() .responseString { response in print("Success: \(response.result.isSuccess)") print("Response String: \(response.result.value)") }
回答4:
The same issue happened to me and it actually ended up being a server issue since the content type wasn't set.
Adding
.validate(contentType: ["application/json"])
To the request chain solved it for me
Alamofire.request(.GET, "url") .validate(contentType: ["application/json"]) .authenticate(user: "", password: "") .responseJSON() { response in switch response.result { case .Success: print("It worked!") print(response.result.value) case .Failure(let error): print(error) } }
回答5:
I got the same error. But i found the solution for it.
NOTE 1: "It is not Alarmofire error", it's bcouse of server error.
NOTE 2: You don't need to change "responseJSON" to "responseString".
public func fetchDataFromServerUsingXWWWFormUrlencoded(parameter:NSDictionary, completionHandler: @escaping (_ result:NSDictionary) -> Void) -> Void { let headers = ["Content-Type": "application/x-www-form-urlencoded"] let completeURL = "http://the_complete_url_here" Alamofire.request(completeURL, method: .post, parameters: (parameter as! Parameters), encoding: URLEncoding.default, headers: headers).responseJSON { response in if let JSON = response.result.value { print("JSON: \(JSON)") // your JSONResponse result completionHandler(JSON as! NSDictionary) } else { print(response.result.error!) } } }
回答6:
This is how I managed to resolve the Invalid 3840 Err.
The error log
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
- It was with Encoding Type used in the Request, The Encoding Type used should be acceptedin your Server-Side.
In-order to know the Encoding I had to run through all the Encoding Types:
default/ methodDependent/ queryString/ httpBody
let headers: HTTPHeaders = [ "Authorization": "Info XXX", "Accept": "application/json", "Content-Type" :"application/json" ] let parameters:Parameters = [ "items": [ "item1" : value, "item2": value, "item3" : value ] ] Alamofire.request("URL",method: .post, parameters: parameters,encoding:URLEncoding.queryString, headers: headers).responseJSON { response in debugPrint(response) }
- It also depends upon the response we are recieving use the appropriate
- responseString
- responseJSON
- responseData
If the response is not a JSON & just string in response use responseString
Example: in-case of login/ create token API :
"20dsoqs0287349y4ka85u6f24gmr6pah"
responseString
回答7:
Maybe it is too late but I solved this problem in another way not mentioned here:
When you use .responseJSON()
, you must set the response header with content-type = application/json
, if not, it'll crash even if your body is a valid JSON. So, maybe your response header are empty or using another content-type.
Make sure your response header is set with content-type = application/json
to .responseJSON()
in Alamofire work properly.
回答8:
The application I was working on this morning had the same error. I believed it to be a server side error since I was unable to upload a user image.
However, upon checking my custom API, I realized that after adding an SSL certificate to my website that I had not updated the api.swift URLs, the data was unable to post:
let HOME_URL = "http://sitename.io" let BASE_URL = "http://sitename.io/api" let UPLOAD_URL = "http://sitename.io/api/user/upload"
I changed the URL's to https://. Problem solved.
回答9:
In my case I have to add this Key: "Accept":"application/json" to my header request.
Something like this:
let Auth_header: [String:String] = ["Accept":"application/json", "Content-Type" : "application/json", "Authorization":"Bearer MyToken"]
I hope that this can help someone.
回答10:
Hey guys this is what I found to be my issue: I was calling Alamofire via a function to Authenticate Users: I used the function "Login User" With the parameters that would be called from the "body"(email: String, password: String) That would be passed
my errr was exactly:
optional(alamofire.aferror.responseserializationfailed(alamofire.aferror.responseserializationfailurereason.jsonserializationfailed(error domain=nscocoaerrordomain code=3840 "invalid value around character 0." userinfo={nsdebugdescription=invalid value around character 0
character 0 is the key here: meaning the the call for the "email" was not matching the parameters: See the code below
func loginUser(email: String, password: String, completed: @escaping downloadComplete) { let lowerCasedEmail = email.lowercased()
let header = [ "Content-Type" : "application/json; charset=utf-8" ] let body: [String: Any] = [ "email": lowerCasedEmail, "password": password ] Alamofire.request(LOGIN_USER, method: .post, parameters: body, encoding: JSONEncoding.default, headers: header).responseJSON { (response) in if response.result.error == nil { if let data = response.result.value as? Dictionary { if let email = data["user"] as? String { self.userEmail = email print(self.userEmail) } if let token = data["token"] as? String { self.token_Key = token print(self.token_Key) }
"email" in function parameters must match the let "email" when parsing then it will work..I no longer got the error...And character 0 was the "email" in the "body" parameter for the Alamofire request:
Hope this helps
answered Nov 14 '17 at 18:20