本文介绍通过NSURLConnection对网上的文件或者图片进行下载,先看代码:
//@property (nonatomic, strong) NSMutableData *mutableData;
NSURL *url = [NSURL URLWithString:[self.updateContentDict valueForKey:@"commons"]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"GET"]; //设置请求方式
[request setTimeoutInterval:30];//设置超时时间
self.mutableData = [[NSMutableData alloc] init];
[self.view makeToast:@"app下载中..."];
[NSURLConnection connectionWithRequest:request delegate:self];//发送一个异步请求
注意Controller需要实现代理方法:NSURLConnectionDataDelegate
#pragma mark - NSURLConnection delegate
//数据加载过程中调用,获取数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//把数据添加进一个属性
[self.mutableData appendData:data];
NSLog(@"%@",self.mutableData);
}
//数据加载完成后调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self dismissHUD];
[self.view makeToast:@"下载完成"];
}
//数据请求失败的时候调用
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"请求网络失败:%@",error);
}