AFHTTPSessionManager網絡下載示例


// 執行下載文件的方法,可以監控下載進度

- (void)downLoadAction

{

    [self.view addSubview:self.numberLabel];

    // 1.創建網絡管理者

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    // 2.目標地址

    NSURL* url = [NSURL URLWithString:@"https://img-blog.csdn.net/20160520141230950?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    

    __weak StartViewController* weakSelf = self;

    __block NSString* cachesBlockStr = nil;

    NSURLSessionDownloadTask *downTask = [manager downloadTaskWithRequest:request progress:^(NSProgress* progress){

        //這裏監控下載進度

        [weakSelf updateProgress:progress];

    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {

        NSLog(@"targetPath is %@",targetPath);

        //下載的目標路徑

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

        cachesBlockStr = cachesPath;

        //path

        NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];

        

        return [NSURL fileURLWithPath:path];

        

    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

        //文件存在filePath下,可以讀出來放到其他文件中,後續文章會介紹

        

    }];

    // 3.啓動任務,resume雖說是重新開始或繼續的意思,但開始也調用這個函數

    [downTask resume];

}

//更新一個label,顯示百分比,label隨便放位置,或者換一個更好看的控件,這個隨意

-(void)updateProgress:(NSProgress*)progress{

    /*

     @property int64_t totalUnitCount;  需要下載文件的總大小

     @property int64_t completedUnitCount; 當前已經下載的大小

     */

    dispatch_async(dispatch_get_main_queue(), ^(void){

        //Run UI Updates

        CGFloat progressf = (CGFloat)progress.completedUnitCount/(CGFloat)(progress.totalUnitCount+1);

        _numberLabel.textColor = [UIColor whiteColor];

        _numberLabel.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.3];

        progressf = progressf*100;

        NSString* showStr = [NSString stringWithFormat:@"%0.f%c",progressf,'%'];

        _numberLabel.text = showStr;

    });

    

    NSLog(@"%lld  %lld",progress.totalUnitCount,progress.completedUnitCount);

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章