Search code examples
iosswiftunicodeglyphicons

Parse unicode character from server, iOS Swift


I use a paid set of linear icon's from this website.

It's great! Especially in iOS I put the .ttf file in my projects bundle, load the font and use it in labels and buttons. I even wrote an article about how I do this.

My problem comes when I want to dynamically change a label based on some server value. My initial instinct was to save the unicode value as text up on the server. I simply save the the value such as ed02 and when I pull it down into my App I add it to, let's say, a label like this.

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
label.font = IconUltimate().icoUltimateFont(18)
let valueFromServer = "ed02"
label.text = "\u{\(valueFromServer)}"

The problem is that the line:

label.text = "\u{\(valueFromServer)}"

is invalid. What am I doing wrong? Is there a way to inject a unicode value from the server into my UI? My solution right now is to map the unicode value from the server using a switch statement like this:

    public func unicodeMapper(rawUnicode: String) -> String {
        switch rawUnicode {
        case "ecf5":
            let thumbs_up = "\u{ecf5}"
            return thumbs_up
        default:
            return ""
        }
    }

And call it like this:

let valueFromServer = "ed02"
label.text = unicodeMapper(rawUnicode: valueFromServer)

Anyone have any suggestions so I don't have to use a switch statement and I can just inject the value from the server?

Thanks


Solution

  • Like this:

    let code = "ecf5" // or whatever you got from the server
    let codeint = UInt32(code, radix: 16)!
    let c = UnicodeScalar(codeint)!
    label.text = String(c)