0

I'm getting unicode scalar for emojis in a text string that I get from a server, which fail to show up as emojis when I print them in a UILabel. This is the format in which I get my string from server:

let string = "Hi, I'm lily U+1F609"

This doesn't work unless it's changed to

let string = "Hi, I'm lily \u{1F609}"

Is there anyway I can convert the string to the required format?

I don't want to use a regex to determine occurrences of U+<HEX_CODE> and then converting them to \u{HEX_CODE}. There has to be a better way of doing this.

Manish Ahuja
  • 4,509
  • 3
  • 28
  • 35
  • You could first remove the `U+` part then use http://stackoverflow.com/questions/32555145/convert-unicode-e-g-1f564-to-emoji-in-swift – Eric Aya Jun 21 '16 at 08:43
  • @EricD the string I get is not going to be the same always. If I remove the U+ part, the remaining string would be `"Hi, I'm lily F609"`. How do I know if `F609` represents a unicode scalar or just string with text `F609` – Manish Ahuja Jun 21 '16 at 09:19
  • You know it because you just removed the `U+` before it. :) Other similar *text to preserve* won't have this prefix. Anyway this is just an idea - the implementation would probably need some adjustments, for sure. – Eric Aya Jun 21 '16 at 09:21

1 Answers1

1

This is the very kind of problems that regex was created for. If there's a simpler non-regex solution, I'll delete this answer:

func replaceWithEmoji(str: String) -> String {
    var result = str

    let regex = try! NSRegularExpression(pattern: "(U\\+([0-9A-F]+))", options: [.CaseInsensitive])
    let matches = regex.matchesInString(result, options: [], range: NSMakeRange(0, result.characters.count))

    for m in matches.reverse() {
        let range1 = m.rangeAtIndex(1)
        let range2 = m.rangeAtIndex(2)

        if let codePoint = Int(result[range2], radix: 16) {
            let emoji = String(UnicodeScalar(codePoint))
            let startIndex = result.startIndex.advancedBy(range1.location)
            let endIndex = startIndex.advancedBy(range1.length)

            result.replaceRange(startIndex..<endIndex, with: emoji)
        }
    }

    return result
}
Code Different
  • 90,614
  • 16
  • 144
  • 163