同步下载,若是内容过大时,不推荐,会阻塞UI。app
- (void)syncDownload异步
{async
NSString *path = @"http://lx.cdn.baidupcs.com/file/test.mp4"; //下载文件地址url
NSURL *url = [NSURL URLWithString:path];spa
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];代理
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];orm
[self save:data];cdn
}ci
- (void)save:(NSData *)data同步
{
NSString *temp = NSTemporaryDirectory();
NSFileManager *fm = [NSFileManager defaultManager];
_path = [temp stringByAppendingPathComponent:@"test.mp4"];
BOOL b = [fm createFileAtPath:_path contents:_data attributes:nil];
}
//异步下载
- (void)asyncDownload
{
NSString *path = @"http://lx.cdn.baidupcs.com/file/test.mp4"; //下载文件地址
NSURL *url = [NSURL URLWithString:path];
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:req delegate:selfstartImmediately:YES];
}
//实现异步下载代理
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"error");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"response");
recLenth = 0;//初始化接收到的长度
_data = [[NSMutableData alloc] initWithCapacity:0];
lenth = [response expectedContentLength];//获取下载内容总长度
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_data appendData:data];//接收到数据
recLenth += [data length];
float pro = (float)recLenth/(float)lenth;//计算下载进度0-1
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"finish");
[self save:_data];
}