0

I need to encode/decode emojis, I'm using this code

var encodeEmoji: String{
        if let encodeStr = NSString(cString: self.cString(using: .nonLossyASCII)!, encoding: String.Encoding.utf8.rawValue){
            return encodeStr as String
        }
        return self
    }

For emojis all is fine, but when I'm coding Accented letters (æ, ø, å) I have something like this \346, \370, \345 Could anyone help to avoid converting of Accented letters, or say, what I'm doing wrong. Thanks in advance!

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Alexander B
  • 137
  • 2
  • 12

1 Answers1

1

One method is to encode each character separately, detecting Emojis:

let testString = "abcdřšá"

let encoded = testString.unicodeScalars
    .map {
        guard $0.isEmoji else { return String($0) }
        let data = String($0).data(using: .nonLossyASCII, allowLossyConversion: true)!
        return String(data: data, encoding: .ascii)!
    }.joined()

print(encoded) // abcdřšá\ud83d\ude03\ud83d\ude03\ud83d\ude03

Using the isEmoji method from this answer.

Sulthan
  • 128,090
  • 22
  • 218
  • 270