skip to Main Content

Twitter Api Response:

"retweet_count" = 0;
            retweeted = 0;
            source = "<a href="http://twitter.com/download/android" rel="nofollow">Twitter for Android</a>";
            text = "ALTIN almU0131U015f baU015fU0131nU0131 gidiyor... bakalU0131m tU00fcrk lirasU0131 daha ne kadar deU011fersizleU015fecek @Turkiye @BorsaAltinU2026 https://twitter.com/i/web/status/1216306036602277889";
            truncated = 1;

My code:

    let request = client.urlRequest(withMethod: "GET", urlString: statusesShowEndpoint, parameters: params, error: &clientError)


    client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
        if connectionError != nil {
            print("Error: (connectionError)")
        }

        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: [])
            print("json: (json)")
        } catch let jsonError as NSError {
            print("json error: (jsonError.localizedDescription)")
        }
    }
}

how can I convert Unicode to string ? i have been don’t use model.

2

Answers


  1. You can use u{Unicode}:

    print("Ainu{2019}t i am a smart boy")
    /* Prints "Ain’t i am a smart boy"
    

    You can Use this Extension as well

    extension String {
        var unescapingUnicodeCharacters: String {
            let mutableString = NSMutableString(string: self)
            CFStringTransform(mutableString, nil, "Any-Hex/Java" as NSString, true)
    
            return mutableString as String
        }
    }
    
    let input = "ALTIN alm\u0131\u015f ba\u015f\u0131n\u0131 gidiyor... bakal\u0131m t\u00fcrk liras\u0131 daha ne kadar de\u011fersizle\u015fecek @Turkiye @BorsaAltin\u2026 https://twitter.com/i/web/status/1216306036602277889"
    
    print("result: (input.unescapingUnicodeCharacters)")
    //ALTIN almış başını gidiyor... bakalım türk lirası daha ne kadar değersizleşecek @Turkiye @BorsaAltin… https://twitter.com/i/web/status/1216306036602277889
    

    enter image description here

    Login or Signup to reply.
  2. I hope this will help.
    I made a playground to test this issue. Swift will complain that the String contains incorrect escape characters.
    This is a problem and the code will not compile:
    enter image description here

    Swift expect the Unicode to be formatted with ex ‘u0131’ or ‘u{0131} but you receive the twitter API with ‘U0131’

    You need to “sanitise” the input first otherwise it will not work! Also when I tested the below I could not save the input in a string with the incorrect escaping. The compiler checks that the strings are correct before doing any operations on them.

    I used a trick. Before saving the input from the file I split into an array of characters with map, of these characters I check with filter which one is an escaping backlash remove it and join the characters again to form a string.
    Sorry but I did not find any other way, just having ‘U’ in my input would get Swift yelling at me.

    enter image description here

    What remains in the input string is “ALTIN almU0131U015f ..etc”

    enter image description here

    Now I need to replace those ‘U0131’ with ‘u0131’ and for this I use Regex:

    enter image description here

    And this is the final output of my String test as property of my struct after the conversion.
    I apologise if my code is a bit messy but it was not easy to get past the string validation in Swift!

    enter image description here

    The below is the playground code in detail.

    What I did is to create a json file with your input as a test:

    enter image description here

    Then create a struct reflecting the JSON properties, in this case only one: “test”

    public struct Test: Codable {
        var test = ""
    }
    
    // this is the initialisation of the empty struct to be filled from json
    var unicodetest: Test = Test()
    
    func parse(json: Data) {
        let decoder = JSONDecoder()
        if let testmodel = try? decoder.decode(Test.self, from: json) {
            unicodetest = testmodel
            print(unicodetest.test)
        }
    }
    
    // Here I get my Json and parse with the above function
    do {
        guard let fileUrl = Bundle.main.url(forResource: "test", withExtension: "json") else { fatalError() }
        let input = try String(contentsOf: fileUrl, encoding: String.Encoding.utf8).map {String($0)}.filter {$0 != "\"}.joined(separator: "")
    if let sanitisedData = input.replacingOccurrences(of: "U(.*?)", with: "\\u$1",  options: .regularExpression).data(using: .utf8){
            parse(json: sanitisedData)
        }
    } catch {
        // if something did not work out 
        print(error)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search