Base64解码NSString的异常结果

时间:2015-04-04 23:00:22

标签: ios objective-c nsstring base64

我一直在讨厌这个问题一个星期。如果有人可以提供方向,我将非常感激。

我已经大大简化了这些基本步骤的问题。

以下是代码:

NSString * data = @"JVBERi0xLjIgDQol4uPP0w0KIA0KOSAwIG9iag0KPDwNCi9MZW5ndGggMTAgMCBSDQovRmlsdGVyIC9GbGF0ZURlY29kZSANCj4-DQpzdHJlYW0NCkiJzZDRSsMwFIafIO_we6eyZuckTZPtbtIWBi0UjYKQGxFbJmpliuLb26QM8X6CJBfJyf99ycmFF6xJagWrrMxzwJeCEMd-gFjWBC1dLPeCJFkbl_fTKfwnTqt1CK0xIZyEwFYZ2T-fwT8KnmIxUmJinNKJyUiyW7mZVEQ6I54m2K3ZzFiupvgPaee7JHFuZqyDvxuGBbZdu8D1y-7jYf-2e__C2KOJm9dxfEqqTHMRXZlR0hRJuKwZau6EJa-MOdjpYN_gprq8xVW7aRp0ZY162ySbktoWvxpPZULGxJLSr-G4UuX-QHrcl_rz_2eqvPgGPPWhqg0KZW5kc3RyZWFtDQplbmRvYmoNCjEwIDAgb2JqDQoyNDYNCmVuZG9iag0KNCAwIG9iag0KPDwNCi9UeXBlIC9QYWdlDQovUGFyZW50IDUgMCBSDQovUmVzb3VyY2VzIDw8DQovRm9udCA8PA0KL0YwIDYgMCBSIA0KL0YxIDcgMCBSIA0KPj4NCi9Qcm9jU2V0IDIgMCBSDQo-Pg0KL0NvbnRlbnRzIDkgMCBSDQo-Pg0KZW5kb2JqDQo2IDAgb2JqDQo8PA0KL1R5cGUgL0ZvbnQNCi9TdWJ0eXBlIC9UcnVlVHlwZQ0KL05hbWUgL0YwDQovQmFzZUZvbnQgL0FyaWFsDQovRW5jb2RpbmcgL1dpbkFuc2lFbmNvZGluZw0KPj4NCmVuZG9iag0KNyAwIG9iag0KPDwNCi9UeXBlIC9Gb250DQovU3VidHlwZSAvVHJ1ZVR5cGUNCi9OYW1lIC9GMQ0KL0Jhc2VGb250IC9C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MDQzM2RkNDg4MmYwNWY4YzEyNDIyMzczND48NDcxNDk1MTA0MzNkZDQ4ODJmMDVmOGMxMjQyMjM3MzQ-XQ0KPj4NCnN0YXJ0eHJlZg0KMjcyNg0KJSVFT0YNCg==";

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:data options:0];

NSLog(@"Decode String Value: %@", decodedData); //prints null .. and thus the problem

为了给问题更多上下文,数据来自gmail rest api附件。附件以base64编码(MIME类型为pdf)。通过获取该附件来检索上面的字符串。我能够通过字面意思正确地解析它在python中:base64.urlsafe_b64decode(data)..所以我知道字符串没有格式错误..我在iOS上做错了什么..只是无法弄清楚到底是什么。

无论如何,如果有人可以帮我解释为什么iOS上的解码失败,你将成为我个人的英雄和救世主。

1 个答案:

答案 0 :(得分:6)

问题在于-_字符的存在,而不是标准的+/字符。如果你替换它们,它可以工作:

NSMutableString *alteredString = [NSMutableString stringWithString:string];
[alteredString replaceOccurrencesOfString:@"-" withString:@"+" options:0 range:NSMakeRange(0, [alteredString length])];
[alteredString replaceOccurrencesOfString:@"_" withString:@"/" options:0 range:NSMakeRange(0, [alteredString length])];
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:alteredString options:0];