Decode base64_encode Image from JSON in Swift

Solution 1:

You have to cast your dictionary value from AnyObject to String. You have also to decode your string data using .IgnoreUnknownCharacters option. Try like this

if let encodedImage = json["image"] as? String,
    imageData =  NSData(base64EncodedString: encodedImage, options: .IgnoreUnknownCharacters),
    image = UIImage(data: imageData) {
    print(image.size)
}

Swift 3.0.1 • Xcode 8.1

if if let encodedImage = json["image"] as? String, 
    let imageData = Data(base64Encoded: encodedImage, options: .ignoreUnknownCharacters),
    let image = UIImage(data: imageData) {
    print(image.size)
}