iosswiftbase64string-decoding

Cannot decode Base64 string swift


I'm trying to decode the following Base64 encoded string :

/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAZKADAAQAAAABAAAAZAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs%2BEJ%2B/8AAEQgAZABkAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5%2Bv/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5%2Bjp6vLz9PX29/j5%2Bv/bAEMABgYGBgYGCgYGCg4KCgoOEg4ODg4SFxISEhISFxwXFxcXFxccHBwcHBwcHCIiIiIiIicnJycnLCwsLCwsLCwsLP/bAEMBBwcHCwoLEwoKEy4fGh8uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLv/dAAQAB//aAAwDAQACEQMRAD8A5RRzQ3ApwppORXkbnqsRT%2BlSZ/WoRx0p2T0oEPY0ufSoycinE/nSEP8AapFqHdUyE4oEPJ4pm7PWkJ600dKaGTDpTxzmoh6VJnAHvT8xodlh0o3P/nNJn8aTPsfypDuf/9DlScc1ESM1XknUDINV/tIPf2rybM9Rsv8AendqpC4BFSCZSDzQ0xXLQx%2BtIxzUe8c0p5ANLURMD39qnHtVVXHSpQwPFKwhxPU03dtxUbPjj0qFnLNj0q0BeU0pfnNVEfjNPDZOfShIZZ3Ubvaq4Zu1LlvWpsVY/9Hyh5ye9V2mPY1SaTioml9a4lA9Bs1PtLDvUgvCKxPMNJvPrT5ES5M6QXw45xU5vwRjNcr5lL5vPWj2aFznVLfDd1qUXwx1rkhMc9acZyO9T7JBznUm%2BX1pUuhk%2B9ckZzkDPvU8dyQetP2Yc52CzDirCsMZrl47v3rSgus8VDgaJmyCcdcUc%2BtU/NLcgmjefU1nZlH/0vCC1RliaZmjNc52Dt3FGaYTSE0xDy1JuphNGaYh%2B7FG4mmE00mhITY/JzmpAxFQCnZp2BFtXI71aiuCvOayw1SB6mw7nRLdgr1Ip32of3jWD5jDpR5r%2BtZ%2BzK52f//T%2Bfc96XPFIPekJrA6x2eKaemKTNJnmmIdmgU2lzQIM%2BlJnmkJpuaaEPzS7qjzxS54pgPyelGcGm03PNAFkOv8VLvSqxOaTIpWC5//1Pn3NNPtSdqaaxOpsdTaM8UUxCmlpBTScGmICaQ0UgoELmkBpvenUwFJpAc00mlFAC4J6Uu003NJQB//1fnjP8qTNH%2BFB7VkjqY3PFO7Uw9Kf/hQSgzxTG60/wDhpjdaoGA5FGaB92k9KBC44zSdqd2pg6UwFpDxS0jdKAGnrSZobrSUAf/Z

It is valid as I have tested it using Online Base64 to Image Converter and it displays fine. I use the following code :

let thumbData = NSData(base64EncodedString: thumbnaill, options: NSDataBase64DecodingOptions(rawValue: 0))
if let b = thumbData {
 let thumb = UIImage(data: b)
 curr_item.thumbnail = thumb

}              

The problem is thumbData is always nil. I'm not sure what I'm doing wrong.


Solution

  • The "base64" data you provided above is URL-encoded. E.g. it has %2B in place of "+" characters. If that's not a copy/paste error, and your actual data is URL-encoded, you need to remove that encoding first before decoding it. Something like this:

    if let decoded = thumbnaill.stringByRemovingPercentEncoding {
      let thumbData = NSData(base64EncodedString: decoded, options: NSDataBase64DecodingOptions(rawValue: 0))
    } else {
      print("Couldn't decode string")
    }