Search code examples
iosjsonswiftswift3alamofire

Unicode characters on JSON string with swift 3 and Alamofire


I'm dealing with this issue here. I have make a json request with alamofire and inside my json there are some characters like u00b etc. Which is greek language. Although when i print the dictionary i cant see the correct string like "αβγ" but their unicode characters.

Which is the proper way with alamofire to unicode all the text that i get to utf-8 so i can print out the proper characters??

The following code is the request that i make.

func getManPerf() {
    Alamofire.request(baseurl, method: .get, parameters: ["action": "categories", "subaction": "getproducts", "category_id": "11", "limit": "0,30"]).responseJSON { (responseData) -> Void in
        if((responseData.result.value) != nil) {
            let result = responseData.result
            print(result)

            if let dict = result.value as? Dictionary<String, AnyObject>{
                if let list = dict["products_in_category"] as? [Dictionary<String, AnyObject>] {

                    for obj in list {
                        let manPerfumes = Products(productDict: obj)
                        self.manPerfumeData.append(manPerfumes)
                    }
                    DispatchQueue.main.async{
                        self.manPerfumeCV.reloadData()

                    }


                }
            }

        }
    }
}

What changes do i have to make to my code so it can bring me the correct data? Thanks!


Solution

  • Format the string with UTF-8 before appending ;)

    let manPerfumesUTF = String(UTF8String: manPerfumes.cStringUsingEncoding(NSUTF8StringEncoding))
    

    Example in playgrounds:

    class Products {
    
        let _name : String
    
        init(productDict : [String : String]) {
    
            self._name = productDict["name"] ?? "error"
        }
    
    }
    
    let productDict = ["name" : "Hugo Boss"]
    let productDictWithUTF8 = ["name" : "\u{03b2}\u{03b5}\u{03b5}\u{03c1}"]
    
    let hugoBoss = Products(productDict: productDict)
    let greekParfume = Products(productDict: productDictWithUTF8)
    print(hugoBoss._name)      // Hugo Boss
    print(greekParfume._name)  // βεερ