Skip to content

Instantly share code, notes, and snippets.

@carlinyuen
Forked from ArtSabintsev/Native Base64 (Pre iOS7)
Last active December 27, 2015 02:49
Show Gist options
  • Save carlinyuen/7254478 to your computer and use it in GitHub Desktop.
Save carlinyuen/7254478 to your computer and use it in GitHub Desktop.
Brilliant little piece of code to help you base64 encode NSStrings in iOS / objective-c using native libraries. Thanks to the original author, Arthur Sabintsev; find his blog here: http://blog.artsabintsev.com/native-base64-encoding-in-ios-pt-1
// Pre-iOS 7
+ (NSString *)base64EncodeString:(NSString *)stringToEncode
{
CFHTTPMessageRef messageRef = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, FALSE);
CFHTTPMessageAddAuthentication(messageRef, NULL, CFSTR("AS"), (__bridge CFStringRef)stringToEncode, kCFHTTPAuthenticationSchemeBasic, FALSE);
CFStringRef authStringRef = CFHTTPMessageCopyHeaderFieldValue(messageRef, CFSTR("Authorization"));
NSString *encodedString = [(__bridge NSString *)authStringRef substringFromIndex:10];
CFRelease(messageRef);
CFRelease(authStringRef);
return encodedString;
}
// For iOS 7
+ (instancetype)encodeBase64String:(NSString *)stringToEncode
{
NSData *dataToEncode = [stringToEncode dataUsingEncoding:NSUTF8StringEncoding];
NSData *encodedData = [dataToEncode base64EncodedDataWithOptions:0];
NSString *encodedString = [[NSString alloc] initWithData:encodedData encoding:NSUTF8StringEncoding];
return encodedString;
}
+ (instancetype)decodeBase64String:(NSString *)stringToDeccode
{
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:stringToDeccode options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
return decodedString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment