How to decode a base 64 string found in a JSON string to generate a UIImage

Clash Royale CLAN TAG#URR8PPPHow to decode a base 64 string found in a JSON string to generate a UIImage
I have pasted my code below. Essentially, I have been given an SDK, which has a JSON string that I then have to parse in order to get to what is a base64 string from which a QR Code is generated. I have been working on it, but the code errors out at the "let nsd = ..." line, with the message: "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
Any help of where I am going wrong would be greatly appreciated. I am a novice when it comes to Swift and programming in general, so am finding this quite challenging. I am also don't think I am correctly converted the response into a JSON, as that is where it is first errorring out.
func qrCodeGenerator(payload : String) {
guard let response = /response as a string from SDK/ else {return}
/* convert response string to an NSData response, so as to convert to JSON in the code below */
let nsd: NSData = NSData(base64Encoded: response, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)!
var jsonResponse = JSON.null
do {
/* convert the response to a json object */
try jsonResponse = JSONSerialization.jsonObject(with: nsd as Data, options: ) as! JSON
/* enter the result array, as the base64 string is contained there */
var result = jsonResponse["result"][0]
var resqr_64 = result["qr_b64"].stringValue
print(resqr_64)
var base64string = resqr_64
/*The base64 string lies beyond the comma*/
var base64image = String(base64string.split(separator: ",")[1]) as String
var decodeString : NSData = NSData(base64Encoded: base64image, options: )!
var decodedimage: UIImage = UIImage(data: decodeString as Data)!
QRCodeImageView.image = decodedimage
} catch {
print(error)
}
}
Any help would be greatly appreciated! Thank you so much.
NSData
Data
let nsd = Data(base64Encoded: response)
qr_b64
1 Answer
1
if let decodedData = Data(base64Encoded: (dataDict["THUMBNAIL"] as? String)! , options: .ignoreUnknownCharacters{
self.imgThumb.image = UIImage(data: decodedData)
}
try this code to get image from base64 string :)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
First of all don't use
NSDatain Swift 3+, use nativeData. Secondly try without optionslet nsd = Data(base64Encoded: response). But I suspect that the response is a regular string and only the value for keyqr_b64is base64 encoded.– vadian
2 mins ago