Journal of development Sorting Thoughts and more…

Native Base64 encoding in iOS7

Posted on Mar 1, 2014 in iOS, Programming

Finally, iOS 7 lets you easy encoding and decoding Base64 string objects without third-party libs. Here is a little unit test which illustrates the encoding and decoding of a NSString object:

- (void) testBase64Encoding
    // NSString --> NSData --> Base64 NSString
    NSString *rawString = @"a test string";
    NSData *rawData = [rawString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64String = [rawData base64EncodedStringWithOptions:0];

    XCTAssertEqualObjects(@"YSB0ZXN0IHN0cmluZw==", base64String, @"wrong base64 string");
    // Base64 NSString --> NSData --> NSString
    NSData *dataFromString = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
    NSString *testResult = [NSString stringWithUTF8String:[dataFromString bytes]];
    XCTAssertEqualObjects(rawString, testResult, @"wrong raw text");

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.