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?
4 Answers
Answers 1
Edit:
Alamofire.request(url, method: .get, parameters: param, encoding: JSONEncoding.default) .responseJSON { response in switch response.result { case .success(let value) : print(response.request) // original URL request print(response.response) // HTTP URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value as! [String:AnyObject]!{ print("JSON: ",JSON) self.arrUser = Mapper<Users>().mapArray(JSONArray:JSON["user"] as! [[String : Any]])! self.tableView.reloadData() } case .failure(let encodingError): //Print error } }
I got the issue that I have added æ in json response and try to print.
Output:
JSON: Optional(<__NSArrayI 0x600000050320>( { "email_address" = "testwts06@gmail.com"; username = "testwts06 \U00e6"; }, { "email_address" = "testwts01@gmail.com"; username = "testwts01 \U00eb"; }, { "email_address" = "testwts100@gmail.com"; username = testwts100; })
While displaying it display in correct format.
Answers 2
Swift 3 update for Ekta's answer:
let encodedURL = specificURL.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
Answers 3
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.
Answers 4
Here is a simple String
extension that solves the issue:
extension String { func fixUnicode() -> String { var copy = self as NSString let regex = try! NSRegularExpression(pattern: "\\\\U([A-Z0-9]{4})", options: .caseInsensitive) let matches = regex.matches(in: self, options: [], range: NSMakeRange(0, characters.count)).reversed() matches.forEach { let char = copy.substring(with: $0.rangeAt(1)) copy = copy.replacingCharacters(in: $0.range, with: String(UnicodeScalar(Int(char, radix: 16)!)!)) as NSString } return copy as String } }
0 comments:
Post a Comment