iOS本地预览和网络预览PDF等文件(二)——PDF等文件缓存在沙盒

项目知识点

PDF等文件缓存在沙盒(cache)

12879926-ab1acd1463a87660.png
1.把网络资源转换成NSData
// 后台返回url
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.model.url]];
// 后台返回字节流数组
NSArray *array = self.model.bytes;
NSInteger length = array.count;
__block Byte *bytes = malloc(length);
// 遍历数组将数组的数据转成byte类型
[array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSInteger value = [[array objectAtIndex:idx] integerValue];
    *(bytes + idx) = value & 0xff;
}];
// 字节数组转换为二进制
NSData *data = [[NSData alloc] initWithBytes:bytes length:length];
2.获取路径
/**
 获取路径

 @param key 文件名+后缀名
 @return 完整的缓存路径
 */
- (NSString *)filePathWithKey:(NSString *)key {
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]
                            stringByAppendingPathComponent:key];
    return cachesPath;
}
3.写入缓存

[data writeToFile:cachesPath atomically:YES]返回值是个BOOL 值,并且是个阻塞的调用,根据返回值即可判断下载结束

/**
 写缓存

 @param data 二进制文件
 @param key 文件名+后缀名
 */
- (void)writeLocalCacheData:(NSData *)data withKey:(NSString *)key {
    // 设置存储路径
    NSString *cachesPath = [self filePathWithKey:key];
    // 判读缓存数据是否存在
    if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) {
        // 删除旧的缓存数据
        [[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil];
    }
    // 存储新的缓存数据
    BOOL result = [data writeToFile:cachesPath atomically:YES];
    if (result) {
        [self.view showToastText:@"下载成功"];
        [self changeBtnStatus];
    }
}

因为会判断数据是否存在,写入缓存前最好在视图上加个提示

[self.view showToastText:@"开始下载,请勿重复点击下载"];
5.改变按钮状态

此时我调用了读取缓存方法

/**
 读缓存

 @param key 文件名+后缀名
 @return 缓存的二级制文件
 */
- (NSData *)readLocalCacheDataWithKey:(NSString *)key {
    NSString *cachesPath = [self filePathWithKey:key];
    // 判读缓存数据是否存在
    if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) {
        // 读取缓存数据
        return [NSData dataWithContentsOfFile:cachesPath];
    }
    return nil;
}

不仅仅是改变按钮文字,也要改变按钮点击事件,也可以在点击事件里作区分

- (void)changeBtnStatus {
    if ([self readLocalCacheDataWithKey:self.model.file_name]) {
        [_button removeTarget:self action:@selector(actionDownload) forControlEvents:UIControlEventTouchUpInside];
        [_button setTitle:@"点击查看" forState:UIControlStateNormal];
        [_button addTarget:self action:@selector(actionView) forControlEvents:UIControlEventTouchUpInside];
    }
}
12879926-bbf040e3e836ebe9.png

另一种文件缓存到沙盒的方法和本地查看、网络预览将在下两篇文章中讲到

猜你喜欢

转载自blog.csdn.net/weixin_34262482/article/details/86901364