I'm trying to convert my UIImage
from a UIImageView
to a string as the data is stored as Base64. I'm using the method below to convert the image but it falls over when trying to update convertedStr.
func convertImg() {
let imageData: NSData = UIImagePNGRepresentation(imageView.image!)! as NSData
convertedStr = NSString(data: imageData as Data, encoding: String.Encoding.utf8.rawValue)!
}
This function is about version 10 as I've tried different ways but the result is always the same. The error returned is
'fatal error: unexpectedly found nil while unwrapping an Optional value' and
'function signature specialization ) -> () to @callee_owned (@unowned Swift.UnsafeBufferPointer) -> (@out ()), Argument Types : [@callee_owned (@unowned Swift.UnsafeBufferPointer) -> ()]> of generic specialization of Swift.StaticString.withUTF8Buffer ((Swift.UnsafeBufferPointer) -> A) -> A'
Could it be that the method I'm using requires a png file and won't work with UIImage
?
In Swift
Encode in swift 2.0 and lower
let image : UIImage = UIImage(named:"imageNameHere")!
//Now use image to create into NSData format
let imageData:NSData = UIImagePNGRepresentation(image)!
let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
Decode
let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!
print(decodedimage)
yourImageView.image = decodedimage