NSURLConnection小文件下载写入沙盒

使用delegate的方式:

@interface ViewController () <NSURLConnectionDataDelegate>
/** 文件数据 */
@property (nonatomic, strong) NSMutableData *fileData;
/** 文件的总长度 */
@property (nonatomic, assign) NSInteger contentLength;
@end

<NSURLConnectionDataDelegate>相关代理方法实现:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSURL *url = [NSURL URLWithString:@"http://www.example.com:8080/resources/videos/minion_15.mp4"];
    [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self];
}

#pragma mark - <NSURLConnectionDataDelegate>
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response{
    self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue];
    self.fileData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.fileData appendData:data];
    CGFloat progress = 1.0 * self.fileData.length / self.contentLength;
    NSLog(@"已下载:%.2f%%", (progress) * 100);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"下载完毕");
    // 将文件写入沙盒中
    // 缓存文件夹
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // 文件路径
    NSString *file = [caches stringByAppendingPathComponent:@"box_minion_15.mp4"];
    NSLog(@"%@",file);
    // 写入数据
    [self.fileData writeToFile:file atomically:YES];
    self.fileData = nil;
}

如果要下载的文件足够小:

- (void)dataDownlaod{
    NSURL *url = [NSURL URLWithString:@"http://www.example.com:8080/resources/images/minion_15.png"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *file = [caches stringByAppendingPathComponent:@"box_minion_15.png"];
    [data writeToFile:file atomically:YES];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,174评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,486评论 25 709
  • 使用NSURLConnection实现下载 1. 小文件下载 第一种方式(NSData) 第二种方式(NSURLC...
    搁浅的青蛙阅读 5,955评论 3 10
  • 身为五音不全,高音上不去,低音下不来的小编,每每看到有人在舞台上一展歌喉都羡慕不已。 有人唱歌能登报纸,小编唱歌却...
    至尚纯K靓饭式KTV阅读 3,449评论 0 1
  • 我有很多我放不下的事情,我放不下曾经付出的真心却换来一个无言的背叛。我放不下自己曾经的努力却换不回一丝的回报。……...
    紫蝶_阅读 2,325评论 0 0

友情链接更多精彩内容