#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];
});
}