There are a few questions similar to this, but most relate to Objective C and I was not able to find a solution.
How can I convert a String to a UIImage in Swift 4? This is what I have so far:
func convertStringToUIImage (image: String) -> UIImage {
let imageData = image.data(using: String.Encoding.utf8)
print ("imageData: ", imageData!)
let base64Image = imageData!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
print ("base64Image: ", base64Image)
let base64ImageAsData = Data(base64Encoded: base64Image as String, options: NSData.Base64DecodingOptions())
print ("base64ImageAsData: ", base64ImageAsData!)
let dataAsUIImage = UIImage(data: base64ImageAsData!)
print ("dataAsUIImage: ", dataAsUIImage)
if dataAsUIImage != nil {
print (dataAsUIImage)
return dataAsUIImage!
} else {
print (dataAsUIImage)
return #imageLiteral(resourceName: "DefaultImage.jpg")
}
}
And that returns the following sequence of events in my console. The first two are from earlier print statements, but that 'lastValue' string is the string I want to convert:
Test Guy
lastValue = 105827994889760
imageData: 15 bytes
base64Image: MTA1ODI3OTk0ODg5NzYw
base64ImageAsData: 15 bytes
dataAsUIImage: nil
nil
The image parameter passed into the function is the result of another function I wrote - convertUIImageToString(image: UIImage). It is stored in a String dictionary:
func convertUIImageToString (image: UIImage) -> String {
var imageAsData: Data = UIImagePNGRepresentation(image)!
var imageAsInt: Int = 0 // initialize
let data = NSData(bytes: &imageAsData, length: MemoryLayout<Int>.size)
data.getBytes(&imageAsInt, length: MemoryLayout<Int>.size)
let imageAsString: String = String (imageAsInt)
return imageAsString
}
Xcode tells me that UIImage(data: dataSource) will return "An initialized UIImage object, or nil if the method could not initialize the image from the specified data." It is returning nil, so why can't it read the data I'm specifying?
Edit: Added my convertUIImageToString function to clarify where the image parameter in convertStringtoUIImage comes from.