網絡通信中關於請求數據、斷點續傳和寫入本地文件

- (void)viewDidLoad {

    [super viewDidLoad];

    NSLog(@"%@",NSHomeDirectory());

    

    //取得已下載數據大小

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    receiveTotal = [[userDefaults objectForKey:@"ReceiveTotal"] doubleValue];

    total = [[userDefaults objectForKey:@"Total"] doubleValue];

    

    //顯示上一次下載的進度

    if (total > 0) {

        CGFloat progress = receiveTotal/total;

        self.progressView.progress = progress;

        self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%", progress * 100];

    }


    

}

- (IBAction)downLoadClick:(UIButton *)sender {

    if (!isDownLoad) {

        

        //1.構建URL

        NSURL *url = [NSURL URLWithString:@"http://s.qdcdn.com/lovebizhi/LoveWallpaper4Mac.dmg"];

        

        //2.構建Request

        NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];

        

        //斷點續傳

        if (receiveTotal > 0) {

            //設置續傳位置

            NSString *position = [NSString stringWithFormat:@"bytes=%d-",(int)receiveTotal];

            [mRequest setValue:position forHTTPHeaderField:@"Range"];

        }

        

        

        //3.發送異步請求

        connection = [NSURLConnection connectionWithRequest:mRequest delegate:self];

        isDownLoad = YES;

        

        //獲取字符串

        NSString *urlStr = url.absoluteString;

        

        //獲取urlStr的最後一部分

        NSString *fileName = [urlStr lastPathComponent];

        

        //寫入文件

        filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",fileName];


        //創建文件

        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];

    }

}


//暫停下載

- (IBAction)pauseClick:(UIButton *)sender {

    //取消下載連接

    [connection cancel];

    connection = nil;

    

    //將緩衝數據寫入文件

    [self appendFileData:self.receiveData];

    

    //在本地保存已下載文件的大小和文件總大小

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    [userDefaults setObject:@(receiveTotal) forKey:@"ReceiveTotal"];

    [userDefaults setObject:@(total) forKey:@"Total"];

 

    //將數據同步寫入文件

    [userDefaults synchronize];

    

    isDownLoad = NO;

}


#pragma mark-NSURLConnectionDataDelegate

//服務器響應

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response{

    

    self.receiveData = [[NSMutableData alloc]init];

    

    //判斷總大小是否爲0,如果爲0,說明從起始位置開始下,獲取文件總大小

    if (total == 0) {

        //獲取所有的響應頭

        NSDictionary *fields = response.allHeaderFields;

        NSLog(@"fields is %@",fields);

        

        //獲取數據的總大小

        NSNumber *length = [fields objectForKey:@"Content-Length"];

        

        total = [length doubleValue];

        

        NSLog(@"total is %.2f",total);


    }

    

}


//接收數據

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    [self.receiveData appendData:data];

    

    receiveTotal += data.length;

    //計算進度

    double progress = receiveTotal / total;

    

    //刷新UI

    self.progressView.progress = progress;

    

    self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%",progress * 100];

    

    //判斷緩衝的數據是否大於500KB

    if (self.receiveData.length >= 500 * 1024) {

        //寫入數據

        [self appendFileData:self.receiveData];

     

        //清空

        self.receiveData.data = nil;

    }

}


//數據傳輸完成

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{


    //將最後一個緩衝文件寫入

    if (self.receiveData.length < 500 * 1024) {

        //寫入數據

        [self appendFileData:self.receiveData];

        

        //清空

        self.receiveData.data = nil;


    }

    _progressLabel.text = @"下載完成";

    self.progressView.progress = 0;


    isDownLoad = NO;

}


- (void)appendFileData:(NSData *)data{

    if (data.length == 0) {

        return;

    }

    

    //使用NSFileHandle寫文件,此文件必須已經創建,NSFileHandle不會創建文件

    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];

    

    //將數據插入到寫入點

    [fileHandle seekToEndOfFile];

    [fileHandle writeData:data];

    

    //關閉文件,確保寫入完成

    [fileHandle closeFile];

    

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章