NSURLConnection下载

2016-10-27  本文已影响4人  nothing_c

下载大中小数据的对应方式


//一般来说:下载在要用get请求

{

//缓存数据

NSMutableData * _buffer;

}

//下载大数据文件

- (void)downloadBigFile {

NSString *str =@"http://localhost:8080/UpLoad/XiaTianXieZouQu.rmvb";

//对路径进行编码去除特殊字符

str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL* url = [NSURL URLWithString:str];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

//导入代理设置代理

[NSURLConnection connectionWithRequest:request delegate:self];

}

#pragma mark -- NSURLConnectionDelegate,NSURLConnectionDataDelegate

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

NSLog(@"接收响应");

_buffer= [[NSMutableData alloc] init];

}

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

NSLog(@"---->%@",data);

[_buffer appendData:data];

}

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

NSLog(@"下载完成");

//设置接收路径

NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/aa.rmvb"];

//写入数据

[_buffer writeToFile:filePath atomically:YES];

NSLog(@"filePath---->%@",filePath);

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

NSLog(@"下载失败");

}

//下载中等文件

- (void)downloadMiddleFile {

//文件资源路径

NSString * str =@"http://localhost:8080/UpLoad/CC.mp3";

str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL* url = [NSURL URLWithString:str];

NSURLRequest * request = [NSURLRequest requestWithURL:url];

[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *_Nullableresponse,NSData *_Nullabledata,NSError *_NullableconnectionError) {

//文件存放路径

NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/cc.mp3"];

NSLog(@"filePath ---->%@",filePath);

//写入文件

[data writeToFile:filePathatomically:YES];

}];

}

//下载小文件直接使用

- (void)downloadSmallFile {

//获取路径

NSString * urlstr =@"http://localhost:8080/UpLoad/5.jpg";

//对URL进行编码,去除特殊字符

urlstr = [urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL*url = [NSURL URLWithString:urlstr];

//设置请求

NSURLRequest * request = [NSURLRequestrequestWithURL:url];

//发送连接

[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *_Nullableresponse,NSData *_Nullabledata,NSError *_NullableconnectionError) {

//刷新UI

[self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:[UIImage imageWithData:data] waitUntilDone:NO];

}];

}

上一篇下一篇

猜你喜欢

热点阅读