AFNetworking监控网络状态以及下载的进度条显示

注:使用AFNetworking加载数据时,首先要添加HTTPs的白名单,设置详解见http://www.cnblogs.com/h-tao/p/5098877.html

判断网络状态:

#pragma mark - 判断网络状态
- (void)judgeNetworkStatus
{
    //原理:看能不能和一个网址连接上;
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"www.baidu.com"]];
    
    //设置网络状态改变的时候 执行的block  参数传入网络状态

    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSArray *arr = @[@"为止",@"不可达",@"wps",@"wifi"];
        
        NSLog(@"%@",arr[status + 1]);
    }];
    
    //开始监控网络状态
    [manager.reachabilityManager startMonitoring];
    
}

下载进度条显示:

#pragma mark - 下载进度,用进度条表达
- (void)textDownload
{
    NSString *urlStr = @"http://imgcache.qq.com/club/item/avatar/zip/7/i87/all.zip";

    //注意:下载进度一般使用AFURLSessionManager
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    
    //参数一:传入URL请求
    //参数二:传入进度对象的地址,使用KVO监控下载进度
    //参数三:block中返回下载文件保存的地址
    NSProgress *progress = nil;
    
    
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        //返回文件下载保存的地址
        NSString *path = [NSString stringWithFormat:@"%@/Documents/text.zip",NSHomeDirectory()];
        NSLog(@"%@",path);
        
        return [NSURL fileURLWithPath:path];
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        
        NSLog(@"下载完成");
        
        NSLog(@"filePath = = = %@",filePath);
    }];
    
    
    //监控下载进度
    [progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    
    _progress = progress;
    
    _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(20, 100, 200, 20)];

    [self.view addSubview:_progressView];
    
    //开始启动下载任务
    [task resume];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    double fractionCompleted = [[object valueForKey:keyPath] doubleValue];
    NSLog(@"下载进度:%f%%",fractionCompleted);
    
    //这个方法在子线程中执行,子线程中不能直接操作UI;
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        _progressView.progress = fractionCompleted;
    }];
}



-(void)dealloc
{
    [_progress removeObserver:self forKeyPath:@"fractionCompleted"];
}

 

posted @ 2016-01-04 14:44  Mr_tao  阅读(2043)  评论(0编辑  收藏  举报