我在下面粘贴了我的代码。从本质上讲,我得到了一个SDK,该SDK具有一个JSON字符串,然后必须解析该JSON字符串,以便获取从中生成QR码的base64字符串。我一直在努力,但是代码错误出现在“ let nsd = ...”行,并显示以下消息:“线程1:致命错误:在展开可选值时意外发现nil”
对我要去哪里的任何帮助将不胜感激。对于Swift和一般编程,我是一个新手,因此发现这非常具有挑战性。我也不认为我将响应正确转换为JSON,因为这是第一次出错的地方。
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)
}
}
任何帮助将不胜感激!非常感谢。
答案 0 :(得分:0)
if let decodedData = Data(base64Encoded: (dataDict["THUMBNAIL"] as? String)! , options: .ignoreUnknownCharacters{
self.imgThumb.image = UIImage(data: decodedData)
}
尝试使用此代码从base64字符串获取图像:)
答案 1 :(得分:0)
代码中有两个严重的问题:
1)响应很可能是常规JSON字符串(非base64编码),无法从字符串初始化base64编码的Data
。
2)您不能使用SwiftyJSON初始化程序强制将JSONSerialization
的结果强制转换为JSON
。
请尝试
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 data = Data(response.utf8)
do {
/* convert the response to a json object */
let jsonResponse = try JSON(data)
/* enter the result array, as the base64 string is contained there */
let result = jsonResponse["result"][0]
let base64string = result["qr_b64"].stringValue
print(base64string)
/*The base64 string lies beyond the comma*/
let base64image = String(base64string.split(separator: ",")[1])
let decodeString = Data(base64Encoded: base64image)!
let decodedimage = UIImage(data: decodeString)!
QRCodeImageView.image = decodedimage
} catch {
print(error)
}
}
注意:您是否不担心一堆 Variable 'xyz' was never mutated; consider changing to 'let' constant
警告?