NSURLConnection 异步下载图片

#pragma mark 下载歌曲
- (IBAction)downloadMP3:(UIButton *)sender {
    NSURL *url = [NSURL URLWithString:@"http://music.baidu.com/data/music/file?link=http://yinyueshiting.baidu.com/data2/music/239130183/12267411954000128.mp3?xcode=1a1fdb87afc200037ed60eb536e08c87&song_id=122674119"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    
    
    
}
#pragma mark 获取服务器响应后调用该方法,只调用一次,获取响应对象
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    //创建mp3Data
    self.mp3Data = [[NSMutableData alloc]init];
    //获取MP3总大小
    self.mp3Length = [response expectedContentLength];
}
#pragma mark 方法是接受到数据 之后回调 调多次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.mp3Data appendData:data];
    self.mp3CurrentLength = self.mp3Data.length;
    self.progressView.progress = self.mp3CurrentLength / self.mp3Length;
    
}
#pragma mark 整个请求完成,数据加载完成之后调用方法
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    self.progressView.progress = 1;
    __autoreleasing NSError *error = nil;
    self.player = [[AVAudioPlayer alloc]initWithData:self.mp3Data error:&error];
    if (error) {
        NSLog(@"error is %@", error);
    } else {
        [self.player play];
    }
    
}

#pragma mark 网络连接错误时回调
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"网络连接错误 error is = %@", error);
}


    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            NSLog(@"出错了");
        } else {
            //在图片视图中显示视图(应该在主线程中更新UI)
            //self.imageView.image = [UIImage imageWithData:data];
            //GCD方式在主线程中更新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                self.imageView.image = [UIImage imageWithData:data];
            });
        }
       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值