Swift Convert string Base64 to UIImage - ios

I'm trying to convert base 64 encoded string to UIImage with the following code:
let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0) )
print(decodedData) //I get data here (It is not nil)
var decodedimage = UIImage(data: decodedData!) //return nil
The decodedData seems fine, Why do I get nil when converting to UIImage?

Try to pass no options, I also recommend using unwrap for optionals :
if let string = base64String {
let decodedData = NSData(base64EncodedString: base64String!, options: [])
if let data = decodedData {
var decodedimage = UIImage(data: data)
} else {
print("error with decodedData")
}
} else {
print("error with base64String")
}

For Swift 4.2
if base64String != nil {
let decodedData = NSData(base64Encoded: base64String!, options: [])
if let data = decodedData {
let decodedimage = UIImage(data: data as Data)
cell.logo.image = decodedimage
} else {
print("error with decodedData")
}
} else {
print("error with base64String")
}

Related

Struggling to parse NSArray to a string with delimiter to produce a QR code in swift

Hi I am currently trying to parse a JSON array produced by alamofire as below:
[
{
"UUID": "31ea524c-4d19-46f7-b3ec-c9264f9dbc78"
},
{
"UUID": "d0c89800-bbae-4189-88ab-503c6b68b511"
}
]
I need to take these values and present them as a comma delimited string so they look like this:
"31ea524c-4d19-46f7-b3ec-c9264f9dbc78, d0c89800-bbae-4189-88ab-503c6b68b511"
Alamofire.request(URL_GET_ORDER, method: .post, parameters: parameters).responseJSON
{
response in
//printing response
print(response)
if let result = response.result.value {
let jsonData = result as! NSArray
}
I need to take the data from the above array pass it to a string and then input that sting into this code to produce a QRcode that can then be scanned as part of a click and collect system:
let myString = "*JOINED STRING GOES HERE*"
// Get data from the string
let data = myString.data(using: String.Encoding.ascii)
// Get a QR CIFilter
guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else { return }
// Input the data
qrFilter.setValue(data, forKey: "inputMessage")
// Get the output image
guard let qrImage = qrFilter.outputImage else { return }
// Scale the image
let transform = CGAffineTransform(scaleX: 10, y: 10)
let scaledQrImage = qrImage.transformed(by: transform)
// Do some processing to get the UIImage
let context = CIContext()
guard let cgImage = context.createCGImage(scaledQrImage, from: scaledQrImage.extent) else { return }
let processedImage = UIImage(cgImage: cgImage)
self.myImageView.image = processedImage
I have already tried a lot of solutions like the following one below:
let stringRepresentation = jsonData.joinWithSeparator("-")
and:
let objCArray = NSMutableArray(array: jsonData)
let swiftArray = objCArray as NSArray as? [String]
print(swiftArray ?? "BrokeAgain!!") // returns nil
let nustr = swiftArray?.joined(separator:",")
The easiest way is to start with Codable data model which represents a single object in your json array.
struct ResponseObject: Codable {
let uuid: String
}
Then you can decode the plain response data into an array of objects – it's easier to work with.
func getUUIDList(_ complection: #escaping (String?) -> Void) {
Alamofire
.request(URL_GET_ORDER, method: .post, parameters: parameters)
.response { response in
guard let data = response.data else {
completion(nil)
return
}
do {
let decoder = JSONDecoder()
let objects = try decoder.decode([ResponseObject].self, from: data)
completion(
objects
.map { $0.uuid }
.joined(separator: ", ")
)
} catch let error {
print(error)
completion(nil)
}
}
}
Finally replace your call Alamofire.request(URL_GET_ORDER, method: .post, parameters: parameters)... with:
// somewhere you call the alamofire
getUUIDList() { responseString in
guard let responseString = responseString else { return }
// Get data from the string
let data = responseString.data(using: String.Encoding.ascii)
// Get a QR CIFilter
guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else { return }
// Input the data
qrFilter.setValue(data, forKey: "inputMessage")
// Get the output image
guard let qrImage = qrFilter.outputImage else { return }
// Scale the image
let transform = CGAffineTransform(scaleX: 10, y: 10)
let scaledQrImage = qrImage.transformed(by: transform)
// Do some processing to get the UIImage
let context = CIContext()
guard let cgImage = context.createCGImage(scaledQrImage, from: scaledQrImage.extent) else { return }
let processedImage = UIImage(cgImage: cgImage)
self.myImageView.image = processedImage
}
Please note, this is just a not testet guideline how you should do it. Do not expect the code will work after copy&paste, but is's a good starting point :)

base64 String to Audio mp3 in iOS?

I have an base64 string and want to convert it into mp3 audio file.
var audioData = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)
print(audioData)
It always returns nil.
let base64String : String = "some sample base64"
let audioData = Data(base64Encoded: base64String, options: .ignoreUnknownCharacters)
if audioData != nil {
if let audData = audioData {
self.playAudio(audioData: audData)
}
}
func playAudio(audioData : Data) {
let filename = documentsDirectory.appendingPathComponent("output.mp3")
do {
try audioData.write(to: filename, options: .atomicWrite)
do {
audioPlayer = try AVAudioPlayer(contentsOf: filename)
guard let player = audioPlayer else { return }
player.prepareToPlay()
player.play()
} catch let error {
print(error.localizedDescription)
}
} catch {
}
}

How to display image from url in swift

I'm making an async call which the JSON response contains both text and url to images that I want to display in a UIImageView. Now displaying the text in a label isn't the problem but loading the images is giving me hard times. Have shared my code below.
//Declared variables to hold response
var offerContent: String?
var offerImage: URL?
var offerTitle: String?
var suggestionLabel:String?
var suggestionScreen: String?
//create a task to send reques
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil {
print("error is:: \(error!.localizedDescription)")
return;
}
//parsing the response
do {
// converting response to NSDictionary
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
DispatchQueue.main.async {
if let parseJSON = myJSON{
var responseCode: Int!
var responseMessage: NSArray!
//getting the json response
responseCode = parseJSON["RESPONSECODE"] as! Int?
responseMessage = parseJSON["RESPONSEMESSAGE"] as! NSArray?
if responseCode == 0 {
for obj in responseMessage{
if let dict = obj as? NSDictionary{
self.offerContent = dict.value(forKey: "CONTENT") as? String
self.offerTitle = dict.value(forKey: "TITLE") as? String
self.suggestionLabel = dict.value(forKey: "SUGGESTION_LABEL") as? String
self.suggestionScreen = dict.value(forKey: "SUGGESTION_SCREEN") as? String
self.offerImage = dict.value(forKey: "IMAGE") as? URL
// print("image:: \(self.offerImage!)")
let offerImageView = UIImageView()
self.darkView.addSubview(offerImageView)
offerImageView.heightAnchor.constraint(equalToConstant: 30).isActive = true
offerImageView.widthAnchor.constraint(equalTo: self.darkView.widthAnchor).isActive = true
offerImageView.topAnchor.constraint(equalTo: self.darkView.topAnchor, constant: 20).isActive = true
offerImageView.image = UIImage(data: self.offerImage)
}
}
}
print(parseJSON)
}
}
}catch{
print("catch:: \(error.localizedDescription)")
}
}
task.resume()
Try this code.
let url = URL(string: "IMAGE URL HERE")
let data = try? Data(contentsOf: url)
if let imageData = data {
let image = UIImage(data: imageData)
}
Import and use Kingfisher
self.imageview.kf.setImage(with: "url")

Crashing with observeForSingleEventOfType

I've got this method:
func fetchImageWithKey(key: String, completion: UIImage -> ()) {
imagesEndPoint.childByAppendingPath(key).observeSingleEventOfType(.Value, withBlock: { snapshot in
guard let imageString = snapshot.value["imageString"] as? String else { return }
guard let imageData = NSData(base64EncodedString: imageString, options: .IgnoreUnknownCharacters), image = UIImage(data: imageData) else { fatalError() }
completion(image)
})
}
Which is called each time a cell is dequeued in cellForRowAtIndexPath. For some reason, whilst scrolling through the tableView, this line guard let imageString = snapshot.value["imageString"] as? String else { return } will hit the else block.
I made sure that the ref does indeed have the key "imageString" and a value of type String in the end. I'm thinking it has something to do with the tableView cell dequeueing, but I'm not sure how I might approach this problem.
Any advice?
Are you sure: snapshot.value is dictionary.
You should check :
if let dic = snapshot.value as? NSDictionary{
guard let imageString = dic["imageString"] as? String else { return }
guard let imageData = NSData(base64EncodedString: imageString, options: .IgnoreUnknownCharacters), image = UIImage(data: imageData) else { fatalError() }
completion(image)
}else{
//
}

"fatal error: unexpectedly found nil while unwrapping an Optional value" while creating UIImage from NSData

Firstly I converted an image into NSData and inserted in the sqlite database with the help of fmdb(flying meat database) in the form of sqlite blob.
Then I retrieved NSData back, but while converting NSData to UIImage I am getting an error "fatal error: unexpectedly found nil while unwrapping an Optional value".
var imageData = String()
let countryDB = FMDatabase(path: databasePath as String )
if countryDB.open() {
let querySQL = "SELECT USERIMAGE FROM USERINFO WHERE ID = \((1))"
let results:FMResultSet? = countryDB.executeQuery(querySQL,
withArgumentsInArray: nil)
if results?.next() == true
{
let correctPicture = (results?.dataForColumn("USERIMAGE"))!
print(correctPicture)
let memberPiC : UIImage = UIImage(data: correctPicture)!
print(memberPiC)
} else {
print("record not found")
}
countryDB.close()
} else {
print("Error: \(countryDB.lastErrorMessage())")
}
This is the code which i used for saving an image
func saveData()
{
var data = NSData()
let contactDB = FMDatabase(path : databasePath as String)
let image = UIImage(named: "back.png")
print(image)
if let unwrappedImage = image {
data = UIImageJPEGRepresentation(unwrappedImage, 1.0)!
print("data" , data)
if contactDB.open()
{
let insertQuery = "INSERT INTO USERINFO( userimage) VALUES('\((data))')"
let result = contactDB.executeUpdate(insertQuery, withArgumentsInArray: nil)
if !result {
print("Error: \(contactDB.lastErrorMessage())")
} else {
}
}
else {
print("Error: \(contactDB.lastErrorMessage())")
}
}
}
here firstly i change UImage into NSData
then convert NSData into base64EncodedString.
After that save this string in a sqlite database in the form of TEXT instead of blob
func saveData()
{
var data = NSData()
let contactDB = FMDatabase(path : databasePath as String)
//insert an image
let image = UIImage(named: "back.png")
print(image)
//convert an image into database NSdata()
if let unwrappedImage = image
{
data = UIImagePNGRepresentation (unwrappedImage)!
print("data" , data)
// convert NSdata to baseEncodeng64
let dataStr = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
print("converted string" ,dataStr)
// save into databse
if contactDB.open()
{
//insert a query
let insertQuery = "INSERT INTO USERINFO( USERIMAGE) VALUES('\((dataStr))')"
let result = contactDB.executeUpdate(insertQuery, withArgumentsInArray: nil)
if !result {
print("Error: \(contactDB.lastErrorMessage())")
} else {
}
}
else {
print("Error: \(contactDB.lastErrorMessage())")
}
}
}
While retrieving an image fetch string data which is stored inside sqlite database as String then convert base64EncodedString into NSdata back. After that convert NSData back to the image.
func fetchData() -> UIImage
{
var decodedimage = UIImage()
var imageDataString = String()
let countryDB = FMDatabase(path: databasePath as String )
if countryDB.open() {
//insert a query to fetch imageStringData
let querySQL = "SELECT USERIMAGE FROM USERINFO WHERE ID = \((1))"
let results:FMResultSet? = countryDB.executeQuery(querySQL,
withArgumentsInArray: nil)
if results?.next() == true
{
imageDataString = (results?.stringForColumn("USERIMAGE"))!
//convert NSString back to NSdata
let decodedData = NSData(base64EncodedString: imageDataString, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
//convert NSdata back to the image
decodedimage = UIImage(data: decodedData!)!
print("retrieve image" , decodedimage)
} else {
print("record not found")
}
countryDB.close()
} else {
print("Error: \(countryDB.lastErrorMessage())")
}
return decodedimage
}

Resources