Alamofire valor no válido alrededor del carácter 0


Alamofire.request(.GET, "url").authenticate(user: "", password: "").responseJSON() {
    (request, response, json, error) in
    println(error)
    println(json)

}

Esta es mi petición con Alamofire, para una cierta petición a veces funciona, pero a veces obtengo:

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

He leído que esto puede deberse a JSON no válido, pero la respuesta es una cadena json estática que he validado en JSON validator como válida. Contiene caracteres å ä ö y algo de HTML.

¿Por qué recibo este error a veces?

Author: Lord Vermillion, 2015-09-02

14 answers

También me enfrenté al mismo problema que intenté responseString en lugar de responseJSON y funcionó .supongo que esto es un error en alamofire al usarlo con django .

 96
Author: Smit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-05 09:58:26

Recibí el mismo error al cargar la imagen en forma de varias partes en Alamofire que estaba usando

multipartFormData.appendBodyPart(data: image1Data, name: "file")

Arreglé reemplazando por

multipartFormData.appendBodyPart(data: image1Data, name: "file", fileName: "myImage.png", mimeType: "image/png")

Espero que esto ayude a alguien.

 9
Author: Avijit Nagare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-22 10:35:49

Que esto te ayude

Alamofire.request(.GET, "YOUR_URL")
     .validate()
     .responseString { response in
         print("Success: \(response.result.isSuccess)")
         print("Response String: \(response.result.value)")
     }
 4
Author: Krutarth Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-18 08:56:05

El mismo problema me sucedió y en realidad terminó siendo un problema de servidor ya que el tipo de contenido no se estableció.

Añadiendo

.validate(contentType: ["application/json"])

A la cadena de peticiones resuelto para mí

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)
            }
        }
 2
Author: cameronmoreau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-01 04:09:06

Tengo el mismo error. Pero encontré la solución.

NOTA 1: "No es un error de Alarmofire", es un error de servidor.

NOTA 2: No es necesario cambiar "responseJSON" a "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!)
            }
        }
    }
 2
Author: Ram Madhavan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-15 07:43:18

Así es como logré resolver el Error 3840 No válido.

El registro de errores

 responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
  1. Fue con el Tipo Encoding utilizado en la Solicitud, El Tipo de codificación utilizado debe aceptarse en su Lado del servidor.

Para conocer la Codificación tuve que ejecutar todos los Tipos de codificación:

Predeterminado/ Dependiente del método/ 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)
     }
  1. también depende de la respuesta estamos recibiendo el
    • responseString
    • responseJSON
    • responseData

Si la respuesta no es una cadena JSON & just en la respuesta, use responseString

Ejemplo : en caso de login/ create token API:

"20dsoqs0287349y4ka85u6f24gmr6pah"

ResponseString

 2
Author: RatZ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-28 09:11:25

Hey chicos, esto es lo que encontré que era mi problema: Estaba llamando a Alamofire a través de una función para Autenticar Usuarios: Usé la función "Login User" Con los parámetros que se llamarían desde el "body"(email: String, password: String) Que se pasarían

Mi error fue exactamente:

Opcional(alamofire.aferror.responseserializationfailed (alamofire.aferror.respuesta a la falla de la publicación.jsonserializationfailed (error domain = nscocoaerrordomain code = 3840 " valor no válido alrededor del carácter 0."userinfo = {nsdebugdescription = valor no válido alrededor del carácter 0

El carácter 0 es la clave aquí: lo que significa que la llamada para el "correo electrónico" no coincidía con los parámetros: Consulte el código a continuación

Func loginUser (email: String, password: String, completed: @escaping downloadComplete) { let lowerCasedEmail = email.minúscula ()

    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" en los parámetros de la función deben coincidir con el let "email" al analizar, entonces funcionará..Ya no tengo la error...Y el carácter 0 era el "email" en el parámetro "body" para la solicitud Alamofire:

Espero que esto ayude

 1
Author: berkat0789,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-14 18:20:17

Tal vez sea demasiado tarde, pero resolví este problema de otra manera no mencionada aquí:

Cuando se utiliza .responseJSON(), debe establecer el encabezado de respuesta con content-type = application/json, si no, se bloqueará incluso si su cuerpo es un JSON válido. Por lo tanto, tal vez su encabezado de respuesta esté vacío o usando otro tipo de contenido.

Asegúrese de que su encabezado de respuesta esté configurado con content-type = application/json a .responseJSON() en Alamofire funcione correctamente.

 0
Author: guijob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-22 21:32:43

La aplicación en la que estaba trabajando esta mañana tenía el mismo error. Creí que era un error del lado del servidor ya que no pude cargar una imagen de usuario.

Sin embargo, al comprobar mi API personalizada, me di cuenta de que después de agregar un certificado SSL a mi sitio web que no había actualizado la api.URL swift, los datos no pudieron publicar:

let HOME_URL = "http://sitename.io"
let BASE_URL = "http://sitename.io/api"
let UPLOAD_URL = "http://sitename.io/api/user/upload"

Cambié la URL a https://. Problema resuelto.

 0
Author: RH Blanchfield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-22 19:47:55

En mi caso tengo que añadir esta Clave: "Accept":"application/json" a mi solicitud de cabecera.

Algo como esto:

let Auth_header: [String:String] = ["Accept":"application/json", "Content-Type" : "application/json", "Authorization":"Bearer MyToken"]

Espero que esto pueda ayudar a alguien.

 0
Author: Dasoga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-18 02:22:42

Resolví usando esto como encabezado:

let header = ["Content-Type": "application/json", "accept": "application/json"]

 0
Author: Bruno Muniz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-19 20:43:57

Estaba enviando el tipo incorrecto (Cadena) al servidor en mis parámetros (necesitaba ser un Int).

 0
Author: agrippa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-19 00:33:24

Me enfrento al mismo problema y el problema está en parámetros.

let params = [kService: service,
                  kUserPath: companyModal.directory_path,
                  kCompanyDomain: UserDefaults.companyDomain,
                  kImageObject: imageString,
                  kEntryArray: jsonString,
                  kUserToken:  UserDefaults.authToken] as [String : Any]

companyModal.directory_path es url. se coaccionó de cadena a cualquier que crea problemas en el lado del servidor. Para resolver este problema, tengo que dar un valor predeterminado que lo convierte en un valor de cadena.

 let params = [kService: kGetSingleEntry,
                  kUserPath: companyModal.directory_path ?? "",
                  kCompanyDomain: UserDefaults.companyDomain,
                  kUserToken: UserDefaults.authToken,
                  kEntryId: id,
                  ] as [String: Any]
 0
Author: Hitesh Agarwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-21 06:16:34

El error se resolvió después de agregar encoding: JSONEncoding.por defecto con 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)
        }
   }
 0
Author: krishnan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-21 13:05:20