Swift base64 decoding returns nil

后端 未结 7 892
-上瘾入骨i
-上瘾入骨i 2020-12-15 06:36

I am trying to decode a base64 string to an image in Swift using the following code:

let decodedData=NSData(base64EncodedString: encodedImageData, options: N         


        
7条回答
  •  粉色の甜心
    2020-12-15 06:57

    Check the content of your decodedData variable and look for this prefix "data:image/png;base64", I had this issue and noticed that my String base64 had a prefix like this, so I used this approached and it worked

    extension String {
    func getImageFromBase64() -> UIImage? {
        guard let url = URL(string: self) else {
            return nil
        }
        do {
            let data = try Data(contentsOf: url)
            return UIImage(data: data)
        } catch {
            return nil
        }
    
    }
    

    }

提交回复
热议问题