Prashant Ghimire
Prashant Ghimire

Reputation: 548

use emoji in label from ios default keyboard

i want to use text input and emoji from iOS default keyboard and send it to server and show that text to label but i am not able to display emojis.it only display text but not emojis. if i do it locally than it will display emoji.

  self.labelName.text = TextFiled.text

output : "test 😘😝"

but when i send send it to server and receive from it from api than emoji is gone. output : "test"

please dont down vote my question without any reason

Upvotes: 0

Views: 1051

Answers (2)

Parth Adroja
Parth Adroja

Reputation: 13514

Swift 3.0 Extension solution:

You need to encode and decode emoji's on iOS side when sending it to server. You can do it as below.

extension String {

    func encodeChatString() -> String? {
        if let encodedTextData = self.data(using: .nonLossyASCII) {
            return String(data: encodedTextData, encoding: .utf8)
        }

        return nil
    }

    func decodeChatString() -> String? {
        let trimmedString = self.trimmingCharacters(in: .whitespacesAndNewlines)
        if let stringData = trimmedString.data(using: .utf8) {
            let messageString = String(data: stringData, encoding: .nonLossyASCII)
            return messageString
        }

        return nil
    }
}

When you send message encode string like below:

message.encodeChatString()

When you receive message decode string like below:

message.decodeChatString()

Upvotes: 2

Himanshu Moradiya
Himanshu Moradiya

Reputation: 4815

When send a data to server use this method .

let data1 = txtMessage.text.dataUsingEncoding(NSNonLossyASCIIStringEncoding)!
let finalmessage = String(data: data1, encoding: NSUTF8StringEncoding)

when you get a response from server before set in label use this method.

 let trimmedString = YOURSERVER_RESPONSE_STRING.stringByTrimmingCharactersInSet(
                NSCharacterSet.whitespaceAndNewlineCharacterSet())
 let data2 = trimmedString.dataUsingEncoding(NSUTF8StringEncoding)!
 let messagestring = String(data: data2, encoding: NSNonLossyASCIIStringEncoding)
 YOURLABEL.text = messagestring as String

Try this your problem solve.

Upvotes: 1

Related Questions