iOS - 小文件下载篇(下载完写入文件)

来源:互联网 发布:如何成为一个网络作家 编辑:程序博客网 时间:2024/05/21 23:34


需要先签 NSURLConnectionDataDelegate协议


- (void)viewDidLoad {

    [superviewDidLoad];

    

    NSString *urlString =@"http://120.25.226.186:32812/resources/videos/minion_15.mp4";

    NSURL *url = [NSURLURLWithString:urlString];

    

    // 下载操作

    [NSURLConnectionconnectionWithRequest:[NSURLRequestrequestWithURL:url]delegate:self];

}


#pragma mark - <NSURLConnectionDataDelegate>

// 下载开始 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {

    

    // 需要下载文件的 总长度

    self.contentLength = [response.allHeaderFields[@"Content-Length"]integerValue];

    // 文件数据

    self.fileData = [NSMutableDatadata];

}



// 下载进行中

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    

    [self.fileDataappendData:data];

    CGFloat progress =1.0 *self.fileData.length /self.contentLength;


    NSLog(@"已下载:%.2f%%", (progress) *100);


    self.progressView.progress = progress;

}



// 下载完成

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    

    NSLog(@"下载完毕");

    

   //将文件写入沙盒中

    // 缓存文件夹

    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)lastObject];

    

    // 文件路径

    NSString *file = [cachesstringByAppendingPathComponent:@"minion_15.mp4"];

    

    // 写入数据

    [self.fileDatawriteToFile:fileatomically:YES];

    self.fileData =nil;

}


一个小例子, 可以没事的时候理解一下~


0 0
原创粉丝点击