注意:此方案沒有對檔案大小作處理,所以大檔案不可使用。(待填坑☹)
所用資源
加密庫 RNCryptor
一款自帶快取的AFN二次封裝 PPNetworkHelper 參考文章 iOS檔案加密-專案中使用
ps:可以先看上面的文章再來看我這篇O(∩_∩)O~
內容下載
使用 PPNetworkHelper的檔案下載功能
+ (NSURLSessionDownloadTask *)Download:(NSString *)urlString parameters:(id)parameters progress:(void (^)(NSProgress *downloadProgress)) progressBlock success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure;
複製程式碼
//由於需要自定義一些配置,所用LYPPNetworkHepler 繼承 PPNetworkHelper此類。
+ (NSURLSessionDownloadTask *)Download:(NSString *)urlString parameters:(id)parameters progress:(void (^)(NSProgress *))progressBlock success:(void (^)(id))success failure:(void (^)(NSError *))failure{
return [LYPPNetworkHepler downloadWithURL:urlString fileDir:@"leejtom" progress:^(NSProgress *progress) {
LYLog(@"download: %@", progress.localizedDescription);
} success:^(NSString *filePath) {
[LYAVPlayerUtils encryptWithFilePath:filePath];
} failure:^(NSError *error) {
LYLog(@"%@",error);
}];
}
複製程式碼
加密
//加密
+ (void)encryptWithFilePath:(NSString *)filePath{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSData *avdata = [NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]];
if (!avdata) {
LYLog(@"檔案不存在");
return;
}
NSError *error;
NSData *encryptAV = [RNEncryptor encryptData:avdata withSettings:kRNCryptorAES256Settings password:@"123456" error:&error];
if (error) {
LYLog(@"encrypt error:%@",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
NSError *error;
LYLog(@"加密:%d",[encryptAV writeToURL:[NSURL URLWithString:filePath] options:NSDataWritingAtomic error:&error]);
if (error) {
LYLog(@"writeToFile error:%@",error);
}
// 解開註釋測試 解密
// else{
// [self decryptWithFilePath:filePath];
// }
});
});
}
複製程式碼
##解密
//解密
+ (void)decryptWithFilePath:(NSString *)filePath{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSData *avdata = [NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]];
if (!avdata) {
LYLog(@"檔案不存在");
return;
}
NSError *error;
NSData *encryptAV = [RNDecryptor decryptData:avdata withPassword:@"123456" error:&error];
if (error) {
LYLog(@"decrypt error:%@",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
NSError *error;
LYLog(@"解密: %d",[encryptAV writeToURL:[NSURL URLWithString:filePath] options:NSDataWritingAtomic error:&error]);
if (error) {
LYLog(@"writeToFile error:%@",error);
}
});
});
}
複製程式碼
遇到的問題
一開始加密一直失敗,斷點發現原來是使用dataWithContentsOfFile獲取data失敗了。改成使用dataWithContentsOfURL 解決這個問題。
- (nullable instancetype)initWithContentsOfFile:(NSString *)path;
- (nullable instancetype)initWithContentsOfURL:(NSURL *)url;