0

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?

user2586519
  • 250
  • 1
  • 6
  • 18

1 Answers1

0

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) }
}
Andrea
  • 26,120
  • 10
  • 85
  • 131
  • no need to unwrap your data when converting your string to utf8 data. It will never fail – Leo Dabus Oct 06 '17 at 06:48
  • 1
    You can just use `Data(.utf8).base64EncodedString()` and remove optional from the return type – Leo Dabus Oct 06 '17 at 06:49
  • Also your methods don't have any parameters so you should make them computed properties check this https://stackoverflow.com/questions/29365145/how-to-encode-string-to-base64-in-swift/43817935#43817935 – Leo Dabus Oct 06 '17 at 06:54
  • didn't know about it, but could you clarify it seems that the method data(using:) returns an optional. I'm using them in playground and they seems to work. – Andrea Oct 06 '17 at 06:54
  • `Data(utf8)` I added a dot by mistake – Leo Dabus Oct 06 '17 at 06:55
  • 1
    All strings in Swift are unicode (utf8). So you are not converting anything. It will never fail – Leo Dabus Oct 06 '17 at 06:56