直接上代码,大家看看能不能理解.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//创建imageview,前面我声明了属性
self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 300, 150, 150)];
self.imageView.backgroundColor = [UIColor yellowColor];
[self.view addSubview:self.imageView];
[_imageView release];
//获取网络的图片网址
NSString *strUrl = @"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";
NSURL *url = [NSURL URLWithString:strUrl];//先把URL转换成string
NSData *data = [NSData dataWithContentsOfURL:url];创建数据接收
UIImage *image = [UIImage imageWithData:data];
self.imageView.image = image;
//用afn进行下载,用mb显示现在的进度,并且把下载的过程放到queue中进行
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//设置标题
hud.labelText = @"正在下载....";
//设置样式
hud.mode = MBProgressHUDModeAnnularDeterminate;
//建立一个网络请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://help.adobe.com/archive/en/photoshop/cs6/photoshop_reference.pdf"]];
//用afn进行下载
//创建一个下载任务
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
//找沙盒路径
NSString *sandBoxpath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *docpath = [sandBoxpath stringByAppendingPathComponent:@"text.pdf"];
NSLog(@"%@", docpath);
//要把PDF文件下载到指定的路径下
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:docpath append:NO];
//在这个boock里能获取到当前的下载进度,hud显示的下载进度就会通过这个block进行设置
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
//设置进度
hud.progress = 1.0 * totalBytesRead / totalBytesExpectedToRead;
}];
//当下载结束的时候,相应的应该移除掉在显示进度的hud,所以要找到关于下载结束的方法,移除hud
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//成功
[hud removeFromSuperview];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//失败
}];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperation:operation];
}
效果图如下,有一个加载效果,一般应该加在下载按钮中
原文:http://www.cnblogs.com/guominghao/p/5045471.html