How to decode \\u00e2\\u0080\\u0099 in iOS - ios

I am getting following characters:
\\u00e2\\u0080\\u0099
from server side and I want to decode this into its correct character which is "`" so please let me know how I can do this in swift.
I don't want to use replace string method as I want a generic solution which should work for all unicode to string conversion.
Thanks,

If you mean "\\u00e2\\u0080\\u0099" the string of 18 characters, you have to unescape it to convert these sequences to their actual values.
This is a possible way to do it:
let input = "located in the heart of Wanchai\\u00e2\\u0080\\u0099s Star"
let str = String(data: input.data(using: .utf8)!, encoding: String.Encoding.nonLossyASCII)
This gives "located in the heart of Wanchaiâs Star".
As has already been said, "\\u00e2\\u0080\\u0099" represents a "â".

Related

How to convert string to raw string in dart

I want to convert an existing string to raw string.
like:
String s = "Hello \n World"
I want to convert this s variable to raw string(I want to print exact "Hello \n Wrold")
I need backslash(\) in output. I am trying to fetch string value from rest api. it have bunch of mathjax(latex) formula containing backslash.
Thanks
You are asking for a way to escape newlines (and possibly other control characters) in a string value.
There is no general way to do that for Dart strings in the platform libraries, but in most cases, using jsonEncode is an adequate substitute.
So, given your string containing a newline, you can convert it to a string containing \n (a backslash and an n) as var escapedString = jsonEncode(string);. The result is also wrapped in double-quotes because it really is a JSON string literal. If you don't want that, you can drop the first and last character: escapedString = escapedString.substring(1, escapedString.length - 1);.
Alternatively, if you only care about newlines, you can just replace them yourself:
var myString = string.replaceAll("\n", r"\n");

What's the (base64Encoded:"aGVsbG8gd29ybGQ") this String meaning?

let data = Data(base64Encoded:"aGVsbG8gd29ybGQ=" ,options:.ignoreUnknownCharacters)
what is the "aGVsbG8gd29ybGQ" meaning???
Language:Swift 3
aGVsbG8gd29ybGQ= means hello world which encoded by base64.
You can check it your self on this site.
Base64 encoding is a way to encode something (this could be hello world, or an image, or anything) to a string value. You can then decode it to get the original data, so aGVsbG8gd29ybGQ= becomes hello word.
An image would turn into a string and decode back to an image (bits / bytes).
The swift example you are giving is decoding the base64 encoded string to a Data object.

Swift: getting character from string (ascii value)

I'm trying to get the character value in ascii and also the character at index.
I have this Objective-C any of you would know the conversion to swift?
po [strToSort characterAtIndex:i] // character x
U+0078 u'x'
po [strToSort UTF8String][i]
x
I'll really appreciate your help.
Updated: you can directly subscript string with an Index
Swift doesn't allow you to subscript Strings with an Integer index. Instead you can construct an index to pass in.
let str = "String with some characters"
let index = str.startIndex.advancedBy(5)
let character = str[index]
print(character) // "g"
For more information on why you can't treat strings as a direct sequence of characters, you can find more info here.
Essentially to be properly unicode compliant, sometimes multiple characters can be combined to create a single character in the final string. This causes issues with naive counting and indexing.
If you want a utf8 representation of the string, String provides a utf8 property as well as a unicodeScalars property for getting the code point for each character.

Swift - remove single backslash

this is maybe stupid question but I'm new to swift and i actually can't figure this out.
I have API which returns url as string "http:\/\/xxx". I don't know how to store URL returned from API in this format. I can't store it to variable because of backslash.
From apple doc:
...string cannot contain an unescaped backslash (\), ...
Is there any way how to store string like this or how remove these single backslashes or how to work with this?
Thank you for every advice.
You can just replace those backslashes, for example:
let string2 = string1.stringByReplacingOccurrencesOfString("\\", withString: "")
Or, to avoid the confusion over the fact that the backslash within a normal string literal is escaped with yet another backslash, we can use an extended string delimiter of #" and "#:
let string2 = string1.stringByReplacingOccurrencesOfString(#"\"#, withString: "")
But, if possible, you really should fix that API that is returning those backslashes, as that's obviously incorrect. The author of that code was apparently under the mistaken impression that forward slashes must be escaped, but this is not true.
Bottom line, the API should be fixed to not insert these backslashes, but until that's remedied, you can use the above to remove any backslashes that may occur.
In the discussion in the comments below, there seems to be enormous confusion about backslashes in strings. So, let's step back for a second and discuss "string literals". As the documentation says, a string literal is:
You can include predefined String values within your code as string literals. A string literal is a fixed sequence of textual characters surrounded by a pair of double quotes ("").
Note, a string literal is just a representation of a particular fixed sequence of characters in your code. But, this should not be confused with the underlying String object itself. The key difference between a string literal and the underlying String object is that a string literal allows one to use a backslash as an "escape" character, used when representing special characters (or doing string interpolation). As the documentation says:
String literals can include the following special characters:
The escaped special characters \0 (null character), \\ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quote) and \' (single quote)
An arbitrary Unicode scalar, written as \u{n}, where n is a 1–8 digit hexadecimal number with a value equal to a valid Unicode code point
So, you are correct that in a string literal, as the excerpt you quoted above points out, you cannot have an unescaped backslash. Thus, whenever you want to represent a single backslash in a string literal, you represent that with a \\.
Thus the above stringByReplacingOccurrencesOfString means "look through the string1, find all occurrences of a single backslash, and replace them with an empty string (i.e. remove the backslash)."
Consider:
let string1 = "foo\\bar"
print(string1) // this will print "foo\bar"
print(string1.characters.count) // this will print "7", not "8"
let string2 = string1.stringByReplacingOccurrencesOfString("\\", withString: "")
print(string2) // this will print "foobar"
print(string2.characters.count) // this will print "6"
A little confusingly, if you look at string1 in the "Variables" view of the "Debug" panel or within playground, it will show a string literal representation (i.e. backslashes will appear as "\\"). But don't be confused. When you see \\ in the string literal, there is actually only a single backslash within the actual string. But if you print the value or look at the actual characters, there is only a single backslash in the string, itself.
In short, do not conflate the escaping of the backslash within a string literal (for example, the parameters to stringByReplacingOccurrencesOfString) and the single backslash that exists in the underlying string.
I found I was having this same issue when trying to encode my objects to JSON. Depending on if you're using the newer JSONEncoder class to parse your JSON and you're supporting a minimum of iOS 13, you can use the .withoutEscapingSlashes output formatting:
let encoder = JSONEncoder()
encoder.outputFormatting = .withoutEscapingSlashes
try encoder.encode(yourJSONObject)
Please check the below code.
let jsonStr = "[{\"isSelected\":true,\"languageProficiencies\":[{\"isSelected\":true,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"English\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Malay\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Chinese\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Tamil\"}]"
let convertedStr = jsonStr.replacingOccurrences(of: "\\", with: "", options: .literal, range: nil)
print(convertedStr)
I've solved with this piece of code:
let convertedStr = jsonString.replacingOccurrences(of: "\\/", with: "/")
To remove single backslash,try this
let replaceStr = backslashString.replacingOccurrences(of: "\"", with: "")
Include a backslash in a string by adding an extra backslash.

Decode base64 to uiimage iOS Swift

decodedData is nil but My base64String contains an extremely long string
Encode
var imgProfile:NSData = UIImagePNGRepresentation(imgUI)
let base64String = imgProfile.base64EncodedStringWithOptions(.allZeros)
Decode
let base64String = prefs.valueForKey("imgDefault") as? String
let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0) )
var decodedimage = UIImage(data: decodedData!)
I"m having trouble outputting my image from base64
base64 string ENCODE before inserting into db:
iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAMAAADDpiTIAAAADFBMVEXFxcX////p6enW1tbAmiBwAAAAHGlET1QAAAACAAAAAAAAAQAAAAAoAAABAAAAAQAAAAYAppse6QAABcxJREFUeAHs3et22jAQReEQ3v+di8sikDaxZeGLdPTxpzS202jP9pwRkNWPDw8EEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQiCVwvV4/p8fl9fH3K7cjsau2sBuBqfKvVf/x+ecnDQJtKSn9qw83DQIpDLqktcV/iECCAGFuXf9Rz6o/5UHPEtTe+t9V0Qj6dGCb6t9d4EBvDrzb+b/3gOlvsqAjB97M/f+rf/+KjUEfDuxU/nsb6APBwD/llsn/UycwDTQt1443/9MGSdCqA4eUXxK0Wv6P917xed7hJc8+m6Uw7A922O1/90MOtGXaweWXA8OXnwINKXAtSe1dzvGWcQManND9nzIZBU434MjZ/1n45zP7gVMVOPX2v1ugCZxowHnp/2wBl4tJ4CwFzm7/DwvEwCkGNND+vwzQBI5XoI32/1CAAUcb0Er7fxggBg41oKH2/2WAJnCcAg3Wf/rU4HEABv+Xmqw/Aw6zsq3x7xEB0596wBEStFt/Boxefwbsb0Br27/XBJie2w7u60Dr9WfA6PVnwJ4GtDz/PbPAXmAvB/qov0lw9PozYB8Dern/pyyQAts70Ojrv8/of33mfYHNBeiq/t4X2L
base64 string DECODE when pulling down from db:
Optional("iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAMAAADDpiTIAAAADFBMVEXFxcX////p6enW1tbAmiBwAAAAHGlET1QAAAACAAAAAAAAAQAAAAAoAAABAAAAAQAAAAYAppse6QAABcxJREFUeAHs3et22jAQReEQ3v
di8sikDaxZeGLdPTxpzS202jP9pwRkNWPDw8EEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQiCVwvV4/p8fl9fH3K7cjsau2sBuBqfKvVf/x
ecnDQJtKSn9qw83DQIpDLqktcV/iECCAGFuXf9Rz6o/5UHPEtTe
t9V0Qj6dGCb6t9d4EBvDrzb b/3gOlvsqAjB97M/f rf/
KjUEfDuxU/nsb6APBwD/llsn/UycwDTQt1443/9MGSdCqA4eUXxK0Wv6P917xed7hJc8
m6Uw7A922O1/90MOtGXaweWXA8OXnwINKXAtSe1dzvGWcQManND9nzIZBU434MjZ/1n45zP7gVMVOPX2v1ugCZxowHnp/2wBl4tJ4CwFzm7/DwvEwCkGNND
vwzQBI5XoI32/1CAAUcb0Er7fxggBg41oKH2/2WAJnCcAg3Wf/rU4HEABv
Xmqw/Aw6zsq3x7xEB0596wBEStFt/Boxefwbsb0Br27/XBJie2w7u60Dr9WfA6PVnwJ4GtDz/PbPAXmAvB/qov0lw9PozYB8Dern/pyyQAts70Ojrv8/of33mfYHNB
There are two different problems:
It would appear that the + characters have been replaced with spaces. That will happen if you submit an application/x-www-form-urlencoded request without percent escaping the + characters. This probably happened when you first sent the base64 string to be stored in the database.
See https://stackoverflow.com/a/24888789/1271826 for a discussion of some percent encoding patterns. The key point here is to not rely upon stringByAddingPercentEscapesUsingEncoding, because that will allow + characters to go unescaped.
The string is also missing the trailing = characters. (The string's length should be a multiple of four, and in this case, it's two characters short, so there should be == at the end of the rendition with the + characters in it (the "before" string). While that is sometimes a mistake made by poorly designed base64-encoders, this is not a problem that base64EncodedStringWithOptions suffers from.
In this case, it looks like a much longer base64 string must have been truncated somehow. (Your strings are suspiciously close to 1024 characters. lol.) This truncation could happen if you put the parameters in the URL rather than the body of the request. But nothing in this code sample would account for this behavior, so the problem rests elsewhere.
But look at the length of the original NSData. The base64 string should be 1/3 larger than that (plus rounded up to the nearest four characters, once you include the trailing = characters).
And, once you decode the string that you've provided and look at the actual contents, you can also see that the base64 string was truncated. (According to the portion provided, there should be 1484 bytes of IDAT data, and there's not, plus there's no IEND chunk ... don't worry about those details, but rest assured that it's basically saying that the PNG data stream is incomplete.)
If you're getting nil returned, then your base64 string is not valid. NSData(base64EncodedString:options:) requires a base64 string that is padded with = to a multiple of 4.
Here's a similar issue (except in Obj-C).
NSData won't accept valid base64 encoded string

Resources