文件下载

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值