Data is not converted into String - ios

I am trying to convert an image into data and then that data into a string using this code but it fail on conversion when i want to convert data into string
let data = UIImagePNGRepresentation(selectedImageImageView.image!)
let datastring = String(data: data!, encoding: .utf8)
it gives some in data, but always nil in datastring
cant figure it out where the problem is if anyone knows please help... thanks

if let img = selectedImageImageView.image {
if let data = UIImagePNGRepresentation(img) {
if let datastring = data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) {
println(datastring)
}
}
}

Related

base64encoded string returned from API call is showing nil after Data(base64encoded: data) is ran

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.

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

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)

How to convert Data received from UIImagePNGRepresentation() to String and vice versa?

This is how I create Data from UIImage:
let data = UIImagePNGRepresentation(image)
And then I need to convert it to String;
if let data = data {
let stringFromData = String(data: data, encoding: .utf8)
}
but stringFromData is nil. Why?
You can get it using the Data method base64EncodedString()
if let data = data {
let stringFromData = data.base64EncodedString()
// to decode base 64 string you can use Data base64Encoded String initializer
if let dataFromBase64 = Data(base64Encoded: stringFromData) {
print(data)
}
}
Convert Your image data in Base64 string
For Encode
let stringFromData : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
And decode
let strBase64 = imageData.base64EncodedStringWithOptions(.allZeros)

Convert NSData to NSString using NSUTF8StringEncoding is not working for special character

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

Resources