#import "TRViewController.h"
@interface TRViewController ()
@property (nonatomic, strong)NSMutableData *allData;
@property (nonatomic)int fileLength;
@end
@implementation TRViewController
- (IBAction)clicked:(id)sender {
NSString *path = @"http://music.baidu.com/data/music/file?link=http://yinyueshiting.baidu.com/data2/music/57899053/39500263198000128.mp3?xcode=f4db023f0362b5b1d65e437b93846cee45b7764643675ea8&song_id=39500263";
NSURL *url = [NSURL URLWithString:path];
//创建http请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (conn) {
NSLog(@"连接成功!!!");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
self.allData = [NSMutableData data];
NSHTTPURLResponse *hr = (NSHTTPURLResponse*)response;
// 字典,通过Content-Length取得文件长度
NSLog(@"%@",hr.allHeaderFields);
self.fileLength = [[hr.allHeaderFields objectForKey:@"Content-Length"] intValue];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.allData appendData:data];
self.myPV.progress = self.allData.length*1.0/self.fileLength;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 完成后将数据保存
[self.allData writeToFile:@"/Users/tangqinglong/Desktop/bbbb.mp3" atomically:YES];
}
//网络出错的话会进到此方法
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
}