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

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)

Related

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

Data is not converted into String

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

Failed when converting UIImage to base64 string

I'm trying to send image to server via JSON string. Problem is the server didn't see my image in PNG or JPG format. Here is code how i do it:
enter image description here
That how i convert parameters to JSON string
enter image description here
What i want - it's encode UIImage to base64 string and send to server.
Thank You!
try using the below code and check if any error occurs or image value is nil
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
if let imageData = UIImageJPEGRepresentation(image, 0.5) {
let base64String = imageData.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
let dict: [String: Any] = ["data": base64String]
do {
let data = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
if let string = String(data: data, encoding: .utf8) {
socket.write(string)
}
} catch {
print(error.localizedDescription)
}
}
}

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 can I convert byte array to base64 string in swift?

When I get my JSON back from my API this is how it looks
{
data:[
100,
80,
105,
99,
etc
]
}
How do I take this array and turn it back into a base64 string, then NSData and finally UIImage.
Here is what I have thus far.
let byteArray = todo["image"]["data"].arrayObject
var data = NSData(bytes: byteArray!, length: byteArray!.count)
var image = UIImage(data: data)
When printing the data it prints fine but returns nil for image.
Have you tried iterating throug the array and building a string from its elements, the use base64 encoding/decoding api to get back from string to NSData? Something like that(I'm writing from iPad so I can't check).
var encodedString=""
for smallString in byteArray {
encodedString += String(smallString)
}
let data = NSData(base64EncodedString: base64Encoded, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
var image = UIImage(data: data)
let byteArray = todo["image"]["data"].arrayObject
let string = String(bytes: byteArray, encoding: .utf8)
let encodedImageData = string
let imageData = NSData(base64Encoded: encodedImageData!)
let image = UIImage(data: imageData! as Data)

Resources