I am trying to decode a base64 string to an image in Swift using the following code:
let decodedData=NSData(base64EncodedString: encodedImageData, options: N
When the number of characters is divisible by 4, you need to avoid padding.
private func base64PaddingWithEqual(encoded64: String) -> String {
let remainder = encoded64.characters.count % 4
if remainder == 0 {
return encoded64
} else {
// padding with equal
let newLength = encoded64.characters.count + (4 - remainder)
return encoded64.stringByPaddingToLength(newLength, withString: "=", startingAtIndex: 0)
}
}
This helped me:
extension String {
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self.replacingOccurrences(of: "_", with: "="), options: Data.Base64DecodingOptions(rawValue: 0)) else {
return nil
}
return String(data: data, encoding: .utf8)
}
}
Usage:
print(base64EncodedString.fromBase64())
Another one-line version:
let length = encoded64.characters.count
encoded64 = encoded64.padding(toLength: length + (4 - length % 4) % 4, withPad: "=", startingAt: 0)
(Swift 3) I been in this situation, Trying to get the data using base64 encoded string returns nil with me when I used this line
let imageData = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)
Tried padding the string and didn't work out too
This is what worked with me
func imageForBase64String(_ strBase64: String) -> UIImage? {
do{
let imageData = try Data(contentsOf: URL(string: strBase64)!)
let image = UIImage(data: imageData)
return image!
}
catch{
return nil
}
}
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
}
}
}
It's make problem with special character, but an interesting point is if we use NSData and NSString then it's working fine.
static func decodeBase64(input: String)->String{
let base64Decoded = NSData(base64Encoded: input, options: NSData.Base64DecodingOptions(rawValue: 0))
.map({ NSString(data: $0 as Data, encoding: String.Encoding.utf8.rawValue) })
return base64Decoded!! as String
}