无法解码Base64字符串swift

时间:2016-06-10 22:57:38

标签: ios swift base64 string-decoding

我尝试解码以下Base64编码的字符串:

/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

它是有效的,因为我使用 Online Base64 to Image Converter 进行了测试,它显示正常。我使用以下代码:

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

}              

问题是thumbData始终为零。我不确定我做错了什么。

1 个答案:

答案 0 :(得分:2)

您在上面提供的“base64”数据是网址编码的。例如。它有%2B代替“+”字符。如果这不是复制/粘贴错误,并且您的实际数据是URL编码的,则需要在解码之前先删除该编码。像这样:

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