网路之ASI 1 - 小下载

今天早上做了这么一个小小的demo,配合quartz-2d (简单的显示下载进度)

1. ASIHTTPRequest
这个框架已经不维护了,不更新了,但是有些功能还是很好用的,所以就初识了一下
导入 CFNETWork.framework
MobileCore..framework
systemConfiguration.framework
libz.dylib
libxml2.dylib

- (void)itemAction {
    // 1. 创建进度条
    _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
    _progressView.frame = CGRectMake(50, 200, 200, 20);
    [self.view addSubview:_progressView];
    
    
#pragma mark - 监听
    
    // 这里需要说明为什么要使用kvo 观察者模式,因为我们无法动态的获取到UIProgressView的进度,所以我们只能通过观察者模式,监听他的progress的属性的变化,然后取到变化的值
    // 这里的监听主要是实时的取到进度条的值
    [_progressView addObserver:self forKeyPath:@"progress" options:NSKeyValueObservingOptionNew context:nil];
    
    _label = [[UILabel alloc] init];
    _label.frame = CGRectMake(50, 170, 200, 30);
    _label.textAlignment = NSTextAlignmentCenter;
    _label.textColor = [UIColor redColor];
    [self.view addSubview:_label];
    
    // 1.5 label
    
    // 2. asi
    // 1-1 创建url
    NSString *urlString = @"http://3.jxdx1.crsky.com/download/StormPlayer1.43.0.exe";
    NSURL *url = [NSURL URLWithString:urlString];
    // 1-2 创建请求,跟NSURLRequest的使用类似
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    
    // 1.将其下载到Documents路径之下
    NSString *downloadPath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@",[urlString lastPathComponent]]];
    
    // 2.设置下载完成路径
    [request setDownloadDestinationPath:downloadPath];
    
    // 3.设置完成后回调的block,
    [request setCompletionBlock:^{
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"finish" message:@"" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alertView show
         ];
        
        [_progressView removeObserver:self forKeyPath:@"progress" context:nil];
    }];
    // 4. 请求设置下载进度条代理,将其给当前进度条
    [request setDownloadProgressDelegate:_progressView];
    // 5. 发送异步请求,将任务交给多线程去做
    [request startAsynchronous];
    

}


// 在监听事件中,取到变化的字典,然后实时获取进度条的值,更新label
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    

    NSNumber *number = [change objectForKey:@"new"];
    
    CGFloat value = [number floatValue];
    
    NSString *valueString = [NSString stringWithFormat:@"%.1f%%",value*100];
    
    _label.text = valueString;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值