Swift 2 JSON 字节数组到 UIImage

Posted

技术标签:

【中文标题】Swift 2 JSON 字节数组到 UIImage【英文标题】:Swift 2 JSON Byte array to UIImage 【发布时间】:2016-07-03 21:52:14 【问题描述】:

我的 ios 应用正在检索一个 JSON 对象,其中包含一个图像字段“文件”。 该字段由服务器以 Base 64 编码

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

我需要在 UIImageView 中加载此字段。我尝试了多种方法都没有成功。这是我的代码的摘录:

        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
        

但是 imageArray 是 nil...知道如何检索该字段(Base 64 Byte 数组)并将其转换为 UIImage 吗?

【问题讨论】:

【参考方案1】:

JSON 不能包含二进制数据。它只能包含字符串、数字、布尔值和空值。你需要自己将base64字符串转成NSData。

imageArray = json!["file"] as? NSData 行替换为以下 5 行。

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

【讨论】:

好的,如何将 imageArray 转换为 UIImage ?我试过 self.ordoPhoto.image = UIImage(data: imageArray!) 但它不起作用。 澄清“它不起作用”是什么意思?它会产生构建时错误吗?导致您的应用程序崩溃?还是总是nil 或其他? 抱歉不清楚......我的 UIImageView ordoPhoto 仍然是空白......即使我使用 self.ordoPhoto.image = UIImage(data: imageArray!) 复制了我的 imageArray 检查imageArray是否为nil。 不是,我可以打印了,内容终于有了

以上是关于Swift 2 JSON 字节数组到 UIImage的主要内容,如果未能解决你的问题,请参考以下文章

Swift 2.0 对象数组到 JSON 字符串

Swift 中的数组到 JSON 数组

PHP JSON 数据到 Xcode Swift 数组

使用 swift 2.1 遍历一个 JSON 命名的字典数组

在swift 3中将字节数组转换为PDF

如何在swift中将json数组保存和检索到用户默认值?