Search code examples
iosswiftuiimageviewbase64animated-gif

how to create GIF from base64 string in swift


I am getting base64 string with extension and I want to convert base64 string to GIF and display it in ImageView. I am using iOSDevCenters+GIF.swift file. I am getting NSData from string but when data converted in image, its giving nil.Below is my code:

let imageData = profileImageString.data(using: .utf8)
self.thumbnailMedia.image = UIImage.gifImageWithData(imageData!)

Does anybody have any ideas on how to do this?


Solution

  • If you are starting from a base64 string, you should decode it as a base64 string not UTF8.

    if let data = Data(base64Encoded: imageDataString) {
        let image = UIImage(data: data)
    }
    

    This snippet simply takes the encode image string, decode into a Data object and create an image from the data.
    If you are working a lot using base64 string I strongly suggest you to extend the String structure functionalities.

    extension String {
        //: ### Base64 encoding a string
        func base64Encoded() -> String? {
            if let data = self.data(using: .utf8) {
                return data.base64EncodedString()
            }
            return nil
        }
    
        //: ### Base64 decoding a string
        func base64Decoded() -> String? {
            if let data = Data(base64Encoded: self) {
                return String(data: data, encoding: .utf8)
            }
            return nil
        }
    }
    

    This snippet was taken from Github, credits to Stringer.

    Also another way is use the extension created by Leo Dabus that is compliant with Swift convention:

    extension String {
        var data:          Data  { return Data(utf8) }
        var base64Encoded: Data  { return data.base64EncodedData() }
        var base64Decoded: Data? { return Data(base64Encoded: self) }
    }
    
    extension Data {
        var string: String? { return String(data: self, encoding: .utf8) }
    }