简体   繁体   English

Swift 2 JSON字节数组到UIImage

[英]Swift 2 JSON Byte array to UIImage

My IOS app is retrieving a JSON Object containing a field "file" which is an image. 我的IOS应用正在检索包含字段“文件”(即图像)的JSON对象。 This field is encoded by the server in Base 64 该字段由服务器在Base 64中编码

JSON Serialization: Optional({
file = "/9j/4AAQSkZJRgABAQAAAQABAAD/........

I would need to load this field in an UIImageView. 我需要在UIImageView中加载此字段。 I tried multiple ways without any success. 我尝试了多种方法,但均未成功。 here is an extract of my code: 这是我的代码的一部分:

        let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        if (error == nil) {

            let json: AnyObject?
            let imageArray: NSData?
            do{
            try json = NSJSONSerialization.JSONObjectWithData(data!, options: [])
                imageArray = json!["file"] as? NSData
                print("JSON file: \(imageArray)")

            }
        catch
        {
            print("error Serialization")
            return
        }

but imageArray is nil...any idea how I can retrieve this field (Base 64 Byte array) and convert it in an UIImage ? 但是imageArray是nil ...我知道如何检索该字段(Base 64 Byte数组)并将其转换为UIImage吗?

JSON cannot contain binary data. JSON不能包含二进制数据。 It can only contain Strings, Numbers, Booleans and Nulls. 它只能包含字符串,数字,布尔值和空值。 You need to convert the base64 String to NSData yourself. 您需要自己将base64字符串转换为NSData。

Replace the line imageArray = json!["file"] as? NSData 将行imageArray = json!["file"] as? NSData替换imageArray = json!["file"] as? NSData imageArray = json!["file"] as? NSData to the following 5 lines. imageArray = json!["file"] as? NSData改为以下5行。

if let fileBase64 = json!["file"] as? String {
    imageArray = NSData(base64EncodedString: fileBase64, options: [])
} else {
    print("missing `file` entry")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM