簡體   English   中英

Swift 2 JSON字節數組到UIImage

[英]Swift 2 JSON Byte array to UIImage

我的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嗎?

JSON不能包含二進制數據。 它只能包含字符串,數字,布爾值和空值。 您需要自己將base64字符串轉換為NSData。

將行imageArray = json!["file"] as? NSData替換imageArray = json!["file"] as? NSData 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