标签:
#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
{
double totalLength;//总时长
double receviewTotal;//下载的长度
NSString *filePath;//文件路径
BOOL isDownLoad;//判断是否已经下载
}
@property (nonatomic , strong)NSMutableData *bufferData;//缓冲数据
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
-(NSMutableData *)bufferData{
if (!_bufferData) {
_bufferData = [NSMutableData data];
}
return _bufferData;
}
- (IBAction)donwAction:(id)sender {
if (!isDownLoad) {
NSURL *url = [NSURL URLWithString:@"http://yinyueshiting.baidu.com/data2/music/134378339/13611644158400128.mp3?xcode=6f254cc3b54ee63ce4d6351b3c1b445d"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// if (receviewTotal>0) {
// NSString *value = [NSString stringWithFormat:@"bytes = %d-",(int)receviewTotal];
//// [request set]
// }
[NSURLConnection connectionWithRequest:request delegate:self];
isDownLoad = YES;
filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/music.mp3"];
NSLog(@"%@",filePath);
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
}else {
UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"当前下载已在本地" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alertView show];
}
}
#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse *httpResPonse =(NSHTTPURLResponse*)response;
NSDictionary *dic = httpResPonse.allHeaderFields;
NSLog(@"%@",dic);
NSNumber *length = [dic objectForKey:@"Content-Length"];
totalLength = [length doubleValue];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.bufferData appendData:data];
receviewTotal+=data.length;
double progess = receviewTotal/totalLength;
self.label.text = [NSString stringWithFormat:@"%0.2f%%",progess*100];
self.progressView.progress = progess;
if (_bufferData.length>500*1000) {
[self appenFileData:_bufferData];
[_bufferData setData:nil];
}
}
-(void)appenFileData:(NSData*)data{
if (data.length==0||filePath.length==0) {
return;
}
NSFileHandle *fileHandle= [NSFileHandle fileHandleForWritingAtPath:filePath];
[fileHandle seekToEndOfFile];
[fileHandle writeData:data];
[fileHandle closeFile];
}
@end
标签:
原文地址:http://blog.csdn.net/emperor_huanzi/article/details/51332646