How to convert string to unicode(UTF-8) string in Swift? - ios

How to convert string to unicode(UTF-8) string in Swift?
In Objective I could write smth like that:
NSString *str = [[NSString alloc] initWithUTF8String:[strToDecode cStringUsingEncoding:NSUTF8StringEncoding]];
how to do smth similar in Swift?

Swift 4 and 5 I have created a String extension
extension String {
func utf8DecodedString()-> String {
let data = self.data(using: .utf8)
let message = String(data: data!, encoding: .nonLossyASCII) ?? ""
return message
}
func utf8EncodedString()-> String {
let messageData = self.data(using: .nonLossyASCII)
let text = String(data: messageData!, encoding: .utf8) ?? ""
return text
}
}

Swift 4:
let str = String(describing: strToDecode.cString(using: String.Encoding.utf8))

Use this code,
let str = String(UTF8String: strToDecode.cStringUsingEncoding(NSUTF8StringEncoding))
hope its helpful

Related

Issue in converting Base64string into string

I am trying to convert base64 string in to string format but I always get nil. My base64 string is "NWQwMDU2ZjhiZjRjYmI2M2MxZTI0NzQzNjAxMjMxMzAyMDh8NjAxMjMxMzAyMDh8NWQwMDU2Zjhi\nZjRjYmI2M2MxZTI0NzQzfDYwMTIzMTMwMjA4fG5hdmlnYXRpb25UZXN0MDA1fDIwMTktMDYtMjEg\nMDk6MzQ6MDB8MA==\n"
After decoding, Is suppose to look like this "5d0056f8bf4cbb63c1e2474360123130208|60123130208|5d0056f8bэ͌Ŕ٥ѥQشĂs3C�".
Here is my code event I tried to remove the "=\n" from string but not succeed.
func qrScanningSucceededWithCode(_ str: String?) {
scanTicketView.qrData = QRData(codeString: str)
let charsToRemove: Set<Character> = Set("=\n")
let newNumberCharacters = String(str!.filter { !charsToRemove.contains($0) })
let decodedString = String(data: Data(base64Encoded: newNumberCharacters)!, encoding: .utf8)!
print(decodedString)
}
This works:
let string = "NWQwMDU2ZjhiZjRjYmI2M2MxZTI0NzQzNjAxMjMxMzAyMDh8NjAxMjMxMzAyMDh8NWQwMDU2Zjhi\nZjRjYmI2M2MxZTI0NzQzfDYwMTIzMTMwMjA4fG5hdmlnYXRpb25UZXN0MDA1fDIwMTktMDYtMjEg\nMDk6MzQ6MDB8MA==\n"
let joined = string.replacingOccurrences(of: "\n", with: "")
if let data = Data(base64Encoded: joined) {
String(data: data, encoding: .utf8)
}

Converting Data to JSON String using Swift in iOS

I have a NSData object which needs to be converted to [String:Any] and here is the code I tried:
let multiOrder = _fields["multiOrder"] as? GPBValue
if let _ = multiOrder {
let data = NSKeyedArchiver.archivedData(withRootObject: multiOrder!)
if let responseString = String(data: data, encoding: .utf8) {
print(responseString)
}
}
GPBValue object looks like NSObject<NSSecureCoding, NSCopying>
But the above code is returning nil

What is the easiest way to create readable JSON string?

I want to draw formatted JSON string with new lines and tabs (or spaces).
But the code below yields string as long one lined text.
let resultString = String(data: response.data, encoding: .utf8)
Is there any default method to create multiline JSON string?
You can use prettyPrinted option of JSONSerialization
do {
let json = try JSONSerialization.jsonObject(with: response.data, options: []) as! [String: AnyObject]
let formattedJson = try JSONSerialization.data(withJSONObject: json, options:JSONSerialization.WritingOptions.prettyPrinted )
if let formattedString = String(data: formattedJson, encoding: .utf8) {
print(formattedString)
}
} catch {
print("Error: \(error)")
}
As for the JSONEncoder introduced in Swift 4, there is a prettyPrinted option:
struct Foo: Codable {
var bar: String
var baz: Int
}
let foo = Foo(bar: "gfdfs", baz: 334)
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted // This makes it formatted as multiline
let data = try encoder.encode(foo)
print(String(data: data, encoding: .utf8)!)
The output is:
{
"bar" : "gfdfs",
"baz" : 334
}

Swift 2.3 - Decode Emoji String [duplicate]

I'm trying to encode and decode Emojis to send them to my database.
I use this to encode:
var comentario = String()
let data = Comment.data(using: String.Encoding.nonLossyASCII, allowLossyConversion: true)
if let data = data {
let emojiString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
comentario = emojiString
}
And it works. But now I don't know how to decode the emoji.
This is the type of encode ---> \ud83d\ude1a
Your encoding code can be simplified to
func encode(_ s: String) -> String {
let data = s.data(using: .nonLossyASCII, allowLossyConversion: true)!
return String(data: data, encoding: .utf8)!
}
Note that it encodes all non-ASCII characters as \uNNNN, not only
Emojis. Decoding is done by reversing the transformations:
func decode(_ s: String) -> String? {
let data = s.data(using: .utf8)!
return String(data: data, encoding: .nonLossyASCII)
}
This returns an optional because it can fail for invalid input.
Example:
let s = "Hello 😃."
let e = encode(s)
print(e) // Hello \ud83d\ude03.
if let d = decode(e) {
print(d) // Hello 😃.
}
Of course you can also define the code as extension methods of the
String type, and you might want to choose better function names.
I fixed this. If you have a server with encode utf8mb4, then for encoding emojis use this code:
var comentario = String()
let data = Comment.data(using: String.Encoding.nonLossyASCII, allowLossyConversion: true)
if let data = data {
let emojiString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
comentario = emojiString
}// comentario contains the emoji encoded
DECODING:
let data = comentarios.data(using: String.Encoding.utf8, allowLossyConversion: false)
if data != nil{
let valueunicode = NSString(data: data!, encoding: String.Encoding.nonLossyASCII.rawValue) as? String
if valueunicode != nil{
comentarios = valueunicode!
}
}//comentarios contantes the deecode string(emoji)

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
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()
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.

Resources