iOS Base64编码解码的两种方法

一、第一种方法 使用GTM第三方类库

iOS Base64编码解码的两种方法_第1张图片
咱们新建一个字符串的分类NSString (Base64)
NSString+Base64.h

#import 

NS_ASSUME_NONNULL_BEGIN

@interface NSString (Base64)

// Base64编码方法1
- (NSString *)base64Encoding;

// Base64解码方法1
- (NSString *)base64Decoding;

@end

NS_ASSUME_NONNULL_END

NSString+Base64.m

#import "NSString+Base64.h"
#import "GTMBase64.h"

@implementation NSString (Base64)

// Base64编码方法1
- (NSString *)base64Encoding {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    
    return [GTMBase64 stringByEncodingData:data];;
}

// Base64解码方法1
- (NSString *)base64Decoding {
    NSData *data = [GTMBase64 decodeData:[self dataUsingEncoding:NSUTF8StringEncoding]];
    
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

@end

测试一下:

#import "ViewController.h"
#import "NSString+Base64.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSString *string = @"abcdefg";              // 常规字符串
    NSString *base64String = @"YWJjZGVmZw==";   // Base64字符串
    
    NSLog(@"Base64编码方法一:%@", [string base64Encoding]);
    NSLog(@"Base64解码方法一:%@", [base64String base64Decoding]);
}

@end
打印输出:
2020-04-05 13:38:27.507954+0800 Base64Demo[3997:87408] Base64编码方法一:YWJjZGVmZw==
2020-04-05 13:38:27.508184+0800 Base64Demo[3997:87408] Base64解码方法一:abcdefg
2020-04-05 13:38:27.508341+0800

二、第二种方法
iOS7.0以后,NSFoundation的NSData自带Base64编码解码的方法,直接调用即可
NSString+Base64.h

#import 

NS_ASSUME_NONNULL_BEGIN

@interface NSString (Base64)

// Base64编码方法2
- (NSString *)base64EncodingString;

// Base64解码方法2
- (NSString *)base64DecodingString;

@end

NS_ASSUME_NONNULL_END

NSString+Base64.m

#import "NSString+Base64.h"

@implementation NSString (Base64)

// Base64编码方法2
- (NSString *)base64EncodingString {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    
    return [data base64EncodedStringWithOptions:0];;
}

// Base64解码方法2
- (NSString *)base64DecodingString {
    NSData *data = [[NSData alloc]initWithBase64EncodedString:self options:0];
    
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

@end

测试一下:

#import "ViewController.h"
#import "NSString+Base64.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSString *string = @"abcdefg";              // 常规字符串
    NSString *base64String = @"YWJjZGVmZw==";   // Base64字符串

    NSLog(@"Base64编码方法二:%@", [string base64EncodingString]);
    NSLog(@"Base64解码方法二:%@", [base64String base64DecodingString]);
}

打印输出:

2020-04-05 13:38:27.508341+0800 Base64Demo[3997:87408] Base64编码方法二:YWJjZGVmZw==
2020-04-05 13:38:27.508462+0800 Base64Demo[3997:87408] Base64解码方法二:abcdefg

你可能感兴趣的:(IOS,Objective-C,base64,ios,objective-c)