14

This code doesn't working with Swift 3 anymore.

imageData = NSData(base64EncodedString: mediaFile, options: NSDataBase64DecodingOptions.fromRaw(0)!)

So is this one.

imageData = NSData(base64EncodedString: mediaFile, options: .allZeros)
Nirav D
  • 71,513
  • 12
  • 161
  • 183
Chris Mikkelsen
  • 3,987
  • 9
  • 29
  • 41

5 Answers5

26

Instead of using NSData use directly Swift 3 native Data.

if let decodedData = Data(base64Encoded: mediaFile, options: .ignoreUnknownCharacters) {
    let image = UIImage(data: decodedData)
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
15

Swift 4.1:

Sometimes string has prefix data:image/png;base64 will make base64Encoded return nil, for this situation:

extension String {
    func base64ToImage() -> UIImage? {
        if let url = URL(string: self),let data = try? Data(contentsOf: url),let image = UIImage(data: data) {
            return image
        }
        return nil
    }
}

Demo code:

let results = text.matches(for: "data:image\\/([a-zA-Z]*);base64,([^\\\"]*)")
for imageString in results {
    autoreleasepool {
        let image = imageString.base64ToImage()
    }
}

extension String {
    func matches(for regex: String) -> [String] {
        do {
            let regex = try NSRegularExpression(pattern: regex)
            let results = regex.matches(in: self, range:  NSRange(self.startIndex..., in: self))
            return results.map {
                //self.substring(with: Range($0.range, in: self)!)
                String(self[Range($0.range, in: self)!])
            }
        } catch let error {
            print("invalid regex: \(error.localizedDescription)")
            return []
        }
    }
}

PS: For more about data uri:

https://en.wikipedia.org/wiki/Data_URI_scheme

https://github.com/nodes-vapor/data-uri

hstdt
  • 5,652
  • 2
  • 34
  • 34
  • Nice answer! Can you please update the code for latest swift? Getting following warnings: 'substring(with:)' is deprecated: Please use String slicing subscript. And "Unused result." both for this: `self.substring(with: Range($0.range, in: self)!)` – Hemang Sep 01 '18 at 02:52
4

Swift

Swift 3.0 does not recommend to use NS any more and the same case with NSData as well

 if let decodedImageData = Data(base64Encoded: mediaFile, options: .ignoreUnknownCharacters) {
        let image = UIImage(data: decodedImageData)
    }

In Objective-C

NSURL *url = [NSURL URLWithString:base64String];    
NSData *decodedImageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:decodedImageData];
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
Deepraj Chowrasia
  • 1,349
  • 10
  • 20
3

I implemented this as UIImage extension

extension UIImage {

    /* 
     @brief decode image base64
     */
    static func decodeBase64(toImage strEncodeData: String!) -> UIImage {

        if let decData = Data(base64Encoded: strEncodeData, options: .ignoreUnknownCharacters), strEncodeData.characters.count > 0 {
            return UIImage(data: decData)!
        }
        return UIImage()
    }
}
EgzonArifi
  • 830
  • 1
  • 11
  • 23
1

You can write like this way

let data = NSData(base64Encoded: mediaFile, options: NSData.Base64DecodingOptions(rawValue: 0))

Hope it will help you

jignesh Vadadoriya
  • 3,244
  • 3
  • 18
  • 29