문자 0 주변의 Alamofire 유효하지 않은 값
Alamofire.request(.GET, "url").authenticate(user: "", password: "").responseJSON() {
(request, response, json, error) in
println(error)
println(json)
}
이것은 Alamofire에 대한 내 요청입니다. 특정 요청에 대해 언젠가 작동하지만 때로는 다음과 같은 메시지가 나타납니다.
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.})
이것이 잘못된 JSON 때문일 수 있다는 것을 읽었지만 응답은 JSON 유효성 검사기에서 유효한 것으로 확인한 정적 json 문자열입니다. å ä ö 문자와 일부 HTML이 포함되어 있습니다.
가끔이 오류가 발생하는 이유는 무엇입니까?
나도 같은 문제에 직면했습니다. responseString
대신 시도했고 responseJSON
작동했습니다. 나는 이것이 Alamofire
함께 사용 하는 버그라고 생각합니다 django
.
Alamofire에서 멀티 파트 형식으로 이미지를 업로드하는 동안 동일한 오류가 발생했습니다.
multipartFormData.appendBodyPart(data: image1Data, name: "file")
나는 다음으로 대체하여 고쳤다.
multipartFormData.appendBodyPart(data: image1Data, name: "file", fileName: "myImage.png", mimeType: "image/png")
이것이 누군가를 돕기를 바랍니다.
같은 문제가 나에게 발생했으며 콘텐츠 유형이 설정되지 않았기 때문에 실제로 서버 문제가되었습니다.
첨가
.validate(contentType: ["application/json"])
요청 체인이 나를 위해 해결했습니다.
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)
}
}
이것이 당신을 도울 수 있습니다
Alamofire.request(.GET, "YOUR_URL")
.validate()
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
}
같은 오류가 발생했습니다. 그러나 나는 그것에 대한 해결책을 찾았습니다.
참고 1 : "Alarmofire 오류가 아닙니다.", 서버 오류 때문입니다.
참고 2 : "responseJSON"을 "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!)
}
}
}
이것이 내가 잘못된 3840 오류를 해결하는 방법입니다.
오류 로그
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
- 그것은 함께 있었다 인코딩 유형 요청에 사용되는 인코딩 유형이 acceptedin해야 사용되는 서버 측 .
인코딩을 알기 위해서는 모든 인코딩 유형을 실행해야했습니다.
기본값 / 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)
}
- 또한 우리가받는 응답에 따라 적절한
- responseString
- responseJSON
- responseData
응답은 응답 사용에 JSON 및 단지 문자열이 아닌 경우 responseString
Example: in-case of login/ create token API :
"20dsoqs0287349y4ka85u6f24gmr6pah"
responseString
I solved using this as header:
let header = ["Content-Type": "application/json", "accept": "application/json"]
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.
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<String, AnyObject> {
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
Error was resolved after adding encoding: JSONEncoding.default with Alamofire.
Alamofire.request(urlString, method: .post, parameters:
parameters,encoding:
JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
In my case , my server URL was incorrect. Check your server URL !!
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.
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.
I was sending the improper type (String) to the server in my parameters (needed to be an Int).
I face same issue and problem is in params.
let params = [kService: service,
kUserPath: companyModal.directory_path,
kCompanyDomain: UserDefaults.companyDomain,
kImageObject: imageString,
kEntryArray: jsonString,
kUserToken: UserDefaults.authToken] as [String : Any]
companyModal.directory_path
is url. it coerced from string to any which create issues at server side. To resolve this issue I have to give default value which make it string value.
let params = [kService: kGetSingleEntry,
kUserPath: companyModal.directory_path ?? "",
kCompanyDomain: UserDefaults.companyDomain,
kUserToken: UserDefaults.authToken,
kEntryId: id,
] as [String: Any]
Probably you have "/" at the end of your path. If it is not GET request, you shouldn't put "/" at the end, otherwise you'll get the error
In my case, there was an extra / in the URL .
I Changed mimeType from "mov" to "multipart/form-data".
Alamofire.upload(multipartFormData: { (multipartFormData) in
do {
let data = try Data(contentsOf: videoUrl, options: .mappedIfSafe)
let fileName = String(format: "ios-video_%@.mov ", profileID)
multipartFormData.append(data, withName: "video", fileName: fileName, mimeType: "multipart/form-data")
} catch {
completion("Error")
}
}, usingThreshold: .init(), to: url,
method: .put,
headers: header)
Worked for me.. :)
참고URL : https://stackoverflow.com/questions/32355850/alamofire-invalid-value-around-character-0
'development' 카테고리의 다른 글
버전 782이므로 데이터베이스를 열 수 없습니다.이 서버는 버전 706 이하를 지원합니다. (0) | 2020.09.21 |
---|---|
자동 초점 =“자동 초점”입니까 아니면 자동 초점입니까? (0) | 2020.09.21 |
docker devmapper 및 CentOS7의 공간 문제 (0) | 2020.09.21 |
Docker compose의 볼륨으로 호스트 디렉토리를 마운트하는 방법 (0) | 2020.09.21 |
Java BigDecimal : 가장 가까운 정수로 반올림 (0) | 2020.09.21 |