Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire 4 and special characters in JSON

I've got a problem with special characters with Alamofire 4.
The JSON contains æ, ø and å and the browser shows them fine, also my previous solution using SwiftyJSON did.

Alamofire 4 shows something like this instead:

U00e6

Using this call:

Alamofire.request(specificURL, method: .get, parameters: param, encoding: URLEncoding.default, headers: nil).responseJSON { (response: DataResponse<Any>) in
    print(response)
}

What to do to solve this?

like image 349
Recusiwe Avatar asked Sep 26 '16 09:09

Recusiwe


People also ask

What does Alamofire mean?

Alamofire is a wrapper for the popular networking library, AFNetworking. It simplifies a lot of the common tasks when dealing with HTTP requests and responses. Alamofire was developed by the engineers at SwiftKick Mobile, LLC in 2011. It was open-sourced to provide a reliable HTTP networking library to iOS developers.

What is the use of Alamofire?

Alamofire is a networking library written in Swift. You use it to make HTTP(S) requests on iOS, macOS and other Apple platforms. For example, to post data to a web-based REST API or to download an image from a webserver. Alamofire has a convenient API built on top of URLSession (“URL Loading System”).

Is Alamofire asynchronous?

Networking in Alamofire is done asynchronously.


2 Answers

Seems the typical serialization error due to wrong JSON encoding, probably your response status code is 3840.

JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32.

You could try to convert the response data to correct UTF8 encoding:

let datastring = NSString(data: response.data!, encoding: String.Encoding.isoLatin1.rawValue)
let data = datastring!.data(using: String.Encoding.utf8.rawValue)
do {
     let object = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
     let jsonDic = object as! NSDictionary
     print("  ok, successfully converted..\(jsonDic)")
} catch let aError as Error {
     // print and handle aError 
}

Hope it helps you.

like image 161
Alessandro Ornano Avatar answered Oct 07 '22 04:10

Alessandro Ornano


Swift 3 update for Ekta's answer:

let encodedURL = specificURL.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
like image 28
alexburtnik Avatar answered Oct 07 '22 03:10

alexburtnik