首页 > 编程语言 > 详细

多线程下载(GCD)

时间:2015-12-14 16:08:50      阅读:241      评论:0      收藏:0      [点我收藏+]

直接上代码,大家看看能不能理解.

- (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];

}

 

 

效果图如下,有一个加载效果,一般应该加在下载按钮中

 技术分享

多线程下载(GCD)

原文:http://www.cnblogs.com/guominghao/p/5045471.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!