GCD多線程同步下載任務

//緩存

//  ViewController.msession

//  多線程下載練習多線程

//異步

//  Created by dc0061 on 15/12/24.async

//  Copyright © 2015 dc0061. All rights reserved.ide

//編碼


#import "ViewController.h"url


@interface ViewController ()<NSURLSessionDownloadDelegate>spa

{.net

    NSMutableArray *_proArray;

    UILabel *_label;

    UILabel *_strUrl;

    UIButton *_down;

    UIProgressView *_pro;

    NSURLSessionDownloadTask *_download;

}

@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    [self layout];

}


- (void) layout{

    _proArray=[NSMutableArray array];

    for (int i=0; i<4; i++) {

        _label = [[UILabel alloc]initWithFrame:CGRectMake(20, 50+120*i, 40, 50)];

        _label.text=@"地址:";

        [self.view addSubview:_label];

        

        _strUrl = [[UILabel alloc]initWithFrame:CGRectMake(70, 50+120*i, 275, 70)];

        _strUrl.text=@"http://dlsw.baidu.com/sw-search-sp/soft/2a/25677/QQ_V4.0.5.1446465388.dmg";

        _strUrl.numberOfLines=3;

        [self.view addSubview:_strUrl];

        

        _pro = [[UIProgressView alloc]initWithFrame:CGRectMake(70, 150+120*i, 275, 70)];

        _pro.tag=i;

        [self.view addSubview:_pro];

        [_proArray addObject:_pro];

        

        _down = [[UIButton alloc]initWithFrame:CGRectMake(50, 500, 275, 70)];

        [_down setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];

        [_down setTitle:@"下載" forState:UIControlStateNormal];

        [_down addTarget:self action:@selector(download) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:_down];

    }

}


- (void) download{

    //建立一個對列

    dispatch_queue_t globalQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    //建立多個線程

    for (int i=0; i<4; i++) {

        //異步執行任務

        dispatch_async(globalQueue, ^{

            [self load:i];

        });

    }

}


- (void) load :(int) index{

    //獲取主線程

    dispatch_queue_t mainQueue=dispatch_get_main_queue();

    //建立下載任務

    dispatch_sync(mainQueue, ^{

        [self beginDownload:index];

    });

}

- (void) beginDownload : (int) index{

    NSString *urlStr=_strUrl.text;

    //將獲取到的字符串進行先進行編碼

    urlStr=[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSURL*url=[NSURL URLWithString:urlStr];

    NSURLRequest *request=[NSURLRequest requestWithURL:url];

    NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration];

    sessionConfig.timeoutIntervalForRequest=20.0;// 請求超時時間

    NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];

    _download=[session downloadTaskWithRequest:request];

    _download.taskDescription=[NSString stringWithFormat:@"%i",index];//增長一個任務描述

    //啓動任務

    [_download resume];

    NSLog(@"下載中");

}


//後面三個參數表明:當前下載量,總的下載量,下載文件的總大小

#pragma  mark 下載中會屢次調用,能夠用來記錄進度條    這個是代理中的方法

- (void) URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{

    int task=[downloadTask.taskDescription intValue];

    // 更新UI 須要在主線程裏面進行

    dispatch_sync(dispatch_get_main_queue(), ^{

    ((UIProgressView *)_proArray[task]).progress=(float)totalBytesWritten/(float)totalBytesExpectedToWrite;

     });

}


#pragma mark 下載完成後調用的方法

- (void) URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{

    //獲取緩存目錄    

    NSString *path=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    NSLog(@"%@",path);

    path=[path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@QQ_V4.0.5.1446465388.dmg",downloadTask.taskDescription]];

    NSURL *saveUrl=[NSURL fileURLWithPath:path];

    //將文件複製到指定目錄

    [[NSFileManager defaultManager] copyItemAtURL:location toURL:saveUrl error:nil];

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

相關文章
相關標籤/搜索