Emojis and Unicode

Q:

Is an Emoji (or Unicode Character) available on a given device?

A:

Maybe. ← Compare against this character!


This article goes into details on how to compare the emoji or Unicode rendition against a known, invalid image.

This approach is very similar to the algorithm I implemented back in 1993, which was the object of a patent application.

It is also the response proposed to Stack Overflow question #41318999, «Is there a way to know if an Emoji is supported in iOS?»

so-logo-320x320SO-41318999



Method: Compare character images

  1. Convert the character into a Portable Network Graphic image, lossless
  2. Extract the png data
  3. Compare the data against a known invalid image
  4. If there is a match, then the character is invalid

This approach leverages on the fact that the OS uses the same default character for unknown unicode character.

Step 1: character to png

func characterData(_ char:Character) -> Data?
{
    let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 10)]
    let charStr = "\(char)" as NSString
    let size = charStr.size(attributes: attributes)

    UIGraphicsBeginImageContext(size)
    charStr.draw(at: CGPoint(x: 0,y :0), withAttributes: attributes)

    var charData:Data? = nil
    if let charImage = UIGraphicsGetImageFromCurrentImageContext() {
        charData = UIImagePNGRepresentation(charImage)
    }

    UIGraphicsEndImageContext()
    return charData
}

Step 2: Compare against a known invalid character

func emojiAvailable(_ emojiCode:Character) -> Bool
{
    let refCode = Character("\u{1f3f6}")

    if let refData = characterData(refCode),
        let testData = characterData(emojiCode) {
        return !(refData as NSData).isEqual(to: testData)
    }
    return false
}

► You can download the full project (Swift + Xcode) and run your own experiment.

Xavier Schott

0010 0000 years of algorithm crafting, software architecture, and bringing visionary mobile apps to market.