溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

網(wǎng)絡通信中關于請求數(shù)據(jù)、斷點續(xù)傳和寫入本地文件

發(fā)布時間:2020-07-03 16:13:25 來源:網(wǎng)絡 閱讀:377 作者:hmymy 欄目:開發(fā)技術

- (void)viewDidLoad {

    [super viewDidLoad];

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

    

    //取得已下載數(shù)據(jù)大小

    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];

        

        //斷點續(xù)傳

        if (receiveTotal > 0) {

            //設置續(xù)傳位置

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

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

        }

        

        

        //3.發(fā)送異步請求

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

        isDownLoad = YES;

        

        //獲取字符串

        NSString *urlStr = url.absoluteString;

        

        //獲取urlStr的最后一部分

        NSString *fileName = [urlStr lastPathComponent];

        

        //寫入文件

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


        //創(chuàng)建文件

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

    }

}


//暫停下載

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

    //取消下載連接

    [connection cancel];

    connection = nil;

    

    //將緩沖數(shù)據(jù)寫入文件

    [self appendFileData:self.receiveData];

    

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

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

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

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

 

    //將數(shù)據(jù)同步寫入文件

    [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);

        

        //獲取數(shù)據(jù)的總大小

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

        

        total = [length doubleValue];

        

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


    }

    

}


//接收數(shù)據(jù)

- (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];

    

    //判斷緩沖的數(shù)據(jù)是否大于500KB

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

        //寫入數(shù)據(jù)

        [self appendFileData:self.receiveData];

     

        //清空

        self.receiveData.data = nil;

    }

}


//數(shù)據(jù)傳輸完成

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


    //將最后一個緩沖文件寫入

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

        //寫入數(shù)據(jù)

        [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寫文件,此文件必須已經(jīng)創(chuàng)建,NSFileHandle不會創(chuàng)建文件

    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];

    

    //將數(shù)據(jù)插入到寫入點

    [fileHandle seekToEndOfFile];

    [fileHandle writeData:data];

    

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

    [fileHandle closeFile];

    

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}



向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI