I have this text: "QWERTY\\\\u0119"
How can I convert this text into normal text without unicode?
I've tried many ways, but nothing in the result. For example I've tried this one:
myString.cString(using: .utf8)
or I've created an extension for String:
func utf8DecodedString()-> String {
let data = self.data(using: .utf8)
if let message = String(data: data!, encoding: .nonLossyASCII){
return message
}
return ""
}
but they are not working. What I'm doing wrong?
Related
I have used the following code to encode/decode the string which has emojis.
extension String {
func encodeEmoji() -> String {
let data = self.data(using: .nonLossyASCII, allowLossyConversion: true)!
return String(data: data, encoding: .utf8)!
}
func decodeEmoji() -> String? {
let data = self.data(using: .utf8)!
return String(data: data, encoding: .nonLossyASCII)
}
}
I have called this function like this below. Converted the response in the 'User' model.
let user = User() // Loaded API's response in this model
let textWithEmoji = user.aboutMe.decodeEmoji() //Here, I am getting the string as the same as before decoding
lblAboutMe.text = textWithEmoji
Following is the encoded string which is not decoding:
"I love too...\n\u2705 Laugh \uD83D\uDE02\n\u2705 Read novels \uD83D\uDCDA\n\u2705 Watch movies \uD83C\uDFAC\n\u2705 Go for bike rides \uD83D\uDEB5\uD83C\uDFFD\u200D\u2640\uFE0F\n\u2705 Go for long walks \uD83D\uDEB6\uD83C\uDFFD\u200D\u2640\uFE0F\n\u2705 Cook \uD83D\uDC69\uD83C\uDFFD\u200D\uD83C\uDF73\n\u2705 Travel \uD83C\uDDEA\uD83C\uDDFA\uD83C\uDDEE\uD83C\uDDF3\uD83C\uDDEC\uD83C\uDDE7\n\u2705 Eat \uD83C\uDF2E\uD83C\uDF5F\uD83C\uDF73\n\u2705 Play board games \u265F\n\u2705 Go to the theatre \uD83C\uDFAD\nMy favourite season is autumn \uD83C\uDF42, i love superhero movies \uD83E\uDDB8\u200D\u2642\uFE0F and Christmas is the most wonderful time of the year! \uD83C\uDF84"
Here is the original text image:
The string you are using is invalid ("I love too...\n\u2705 Laugh \uD83D\uDE02\n\u2705 Read novels \uD83D\uDCDA\n\u2705 Watch movies \uD83C\uDFAC\n\u2705")
It should be in valid String literal
"\\uD83D\\uDCDA\\u2705"
You have a string non-BMP characters in form of JSON String. And your decodeEmoji cannot convert them into valid characters.
So we need to forcefully convert such strings.
extension String {
var jsonStringRedecoded: String? {
let data = ("\""+self+"\"").data(using: .utf8)!
let result = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as! String
return result
}
}
After that you need to decode emoji from above string using below function.
extension String {
var decodeEmoji: String? {
let data = self.data(using: String.Encoding.utf8,allowLossyConversion: false);
let decodedStr = NSString(data: data!, encoding: String.Encoding.nonLossyASCII.rawValue)
if decodedStr != nil{
return decodedStr as String?
}
return self
}
}
Usually JSON decoder can decode these type of characters into emoji
May be there is chances of invalid JSON
First need to verify these things that json is valid or not before using.
USAGE:
let jsonDecodedString = "Your string".jsonStringRedecoded
let decodedEmojiText = jsonDecodedString?.decodeEmoji
debugPrint("\(decodedEmojiText)")
I am very confused on this one. I had been thinking it was something wrong with my server, but after testing it seems as though using Data(base64encoded: data) is producing nil even though the data is there and is in fact base64encoded.
I have tried everything I can think of and nothing is working. Here is the code I am using and the output...
do {
print("DATA as a string: ", String(data: data!, encoding: .utf8) ?? "NONE AVAILABLE")
let decodedData = Data(base64encoded: data!, options: .ignoreUnknownCharacters)
print("DECODED DATA: ")
print(decodedData as Any)
let apiResponse = try JSONDecoder().decode(ApiConnectionResponse.self, from: decodedData!)
completion(.success(apiResponse))
} catch {
completion(.failure(error))
}
The output from that is...
Data as string:
eyJzdWNjZXNzIjoiZmFsc2UiLCJlcnJvciI6Im1vYmlsZV9waW5fY29ubmVjdDogaW52YWxpZCBvciBleHBpcmVkIn0.
DECODED DATA: nil
So the String is a legit base64encoded string, it decodes to
{"success":"false","error":"mobile_pin_connect: invalid or expired"}
However the decoded data is nil. I don't understand, how can it be nil when the string is a base64encoded string and is not nil.
I have even tried forcing the string in there like so...
let decodedData = Data(base64encoded: String(data: data!, encoding: .utf8))
Still no luck. It is throwing a fatal error, and I can see in the section at the bottom of Xcode that the data is in fact "(Data?) 92 bytes" What I can't figure out is why it is nil after running through Data()...
Any help would be greatly appreciated, I am really lost and can't figure out why I can make the string, but not the data.
The end result of this is, I need to get JSONDecoder().decode to work with the reply from the server, I think I can get that part done, if I can figure out why it is nil after the data call. Thank you.
You need to check your data length, divide by 3 and in case the result is not zero add one or two bytes (65) = equal sign for padding your data. Try like this:
let decodedData = Data(base64Encoded: data + .init(repeating: 65, count: data.count % 3))
extension Data {
var base64encodedDataPadded: Data {
let data = last == 46 ? dropLast() : self
return data + .init(repeating: 65, count: data.count % 3)
}
}
Playground testing:
let data = Data("eyJzdWNjZXNzIjoiZmFsc2UiLCJlcnJvciI6Im1vYmlsZV9waW5fY29ubmVjdDogaW52YWxpZCBvciBleHBpcmVkIn0.".utf8)
let decodedData = Data(base64Encoded: data.base64encodedDataPadded)!
print(String(data: decodedData, encoding: .utf8)!) // "{"success":"false","error":"mobile_pin_connect: invalid or expired"}"
I guess the encoded data is wrong.
let originalString = """
{"success":"false","error":"mobile_pin_connect: invalid or expired"}
"""
let base64string = originalString.data(using: .utf8)?.base64EncodedString()
print(base64string)
let base64EncodedData = originalString.data(using: .utf8)?.base64EncodedData()
let base64EncodedString = String(data: base64EncodedData!, encoding: .utf8)
print(base64EncodedString)
let decodedData = Data(base64Encoded: base64EncodedData!)
let decodedString = String(data: decodedData!, encoding: .utf8)
print(decodedString)
The log is as below:
Optional("eyJzdWNjZXNzIjoiZmFsc2UiLCJlcnJvciI6Im1vYmlsZV9waW5fY29ubmVjdDogaW52YWxpZCBvciBleHBpcmVkIn0=")
Optional("eyJzdWNjZXNzIjoiZmFsc2UiLCJlcnJvciI6Im1vYmlsZV9waW5fY29ubmVjdDogaW52YWxpZCBvciBleHBpcmVkIn0=")
Optional("{\"success\":\"false\",\"error\":\"mobile_pin_connect: invalid or expired\"}")
According to the base64 specification, . is not a valid character. = is the appropriate character for padding.
https://en.wikipedia.org/wiki/Base64
You show your base64 string as having a period and a newline at the end. That doesn't look correct. An online base64 decoder decodes it with or without that final period and newline, but Swift probably chokes with it in place.
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)
}
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.
I want to parse a CSV file to create a String.
I fetch the data with the Dropbox API. Let's say my CSV file contains a simple word: "école". When I try to create a String I get the error: fatal error: unexpectedly found nil while unwrapping an Optional value.
My code:
client.files.download(path: "/\(selectedFile)", destination: destination).response { response, error in
if let (_, url) = response {
let data = NSData(contentsOfURL: url)
print("data: \(data!)")
let myString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
let csv = CSwiftV(String: myString)
} else {
print(error!)
}
}
The print("data: \(data!)") works well, it prints a bunch of hexadecimal. So I understand my data are not nil (right?).
If my CSV file contains the word "ecole" instead of "école" it works perfectly. But as far as I know, UTF-8 encoding should support special character no?
It means that your data is encoded in other code rather NSUTF8StringEncoding decode it with the same encoding
For Example
let string = "école"
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
let myString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String //This is OK
let string = "école"
let data = string.dataUsingEncoding(NSUnicodeStringEncoding)
let myString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String // This will not work and myString will be nil
And please try to avoid force Unwrap (!) even if you are sure that you have data there, because you can have a crash next time you use !
I would do it like this instead:
guard let data = NSData(contentsOfURL: url),
let myString = NSString(data: data, encoding: NSUTF8StringEncoding) else {
print("something terrible happened treat error")
}
let csv = CSwiftV(String: String(myString))