網絡(下載)

準備:

NSString *urlString = @"http://127.0.0.1/dawenjian.zip";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

1.NSURLConnection:異步回調下載

  • 發送 GET 請求
// 同步:localResponse 為 nil,用來接受本地請求返回的響應。
[NSURLConnection sendSynchronousRequest:localRequest returningResponse:&localResponse error:NULL];

// 異步
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
  NSLog(@"response:%@",response);
    }];
    


  • NSURLConnectionDownloadDelegate:3個代理方法
    1. 做下載進度條使用。
    2. 只能堅挺下載進度,但文件下載完成之后找不到下載文件
//  設置 NSConnection 代理
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

@optional
1. // 檢測下載過程(下載進度條使用!)//多次調用的下載方法!
// bytesWritten: 本次下載(本次調用這個方法)寫入(下載)的數據量
// totalBytesWritten :目前為止,已經寫入(下載)的數據總量
// expectedTotalBytes: 需要下載的文件的大小(需要寫入的總數據量)
- (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes;

2. // 斷點續傳的方法,沒用。
- (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes;

@required
3. // 下載完成之后,調用的方法!
// destinationURL:網絡下載完成之后,文件存儲的路徑!
// destinationURL:網絡下載完成之后,文件存儲的路徑!
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *) destinationURL;

  • NSURLConnectionDataDelegate
1. // 接收到服務器響應的時候,就會調用!
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

2. // 開始接受服務器響應的數據的時候就會調用
// 多次調用,每次下載一點數據,直到數據下載完畢!
// data : 本次下載接受的數據!
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

3. // 下載完成之后,就會調用!
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{

    • (void)start; 開始連接
    • (void)cancel; 取消連接

2.NSFileHandle:句柄,在下載文件過程中,內存沒有飆升


// 開始接受數據的時候會調用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    //創建句柄
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:self.filePath];
    if (fileHandle) {
        //把句柄移動到文件末尾
        [fileHandle seekToEndOfFile];
        [fileHandle writeData:data];
    }else{
    //當路徑下邊還沒有 文件的時候調用
        [data writeToFile:self.filePath atomically:YES];
    }
    NSLog(@"data.length%ld",data.length);
}

3.HEAD:只獲取響應頭信息,不要實體內容.但是?。?!這個方法會重新加載本地文件到內存中,由加載的文件大小決定線程卡住的時間


// 因為HEAD請求,只獲取響應頭信息,數據量比較少,所以一般使用同步方法發送!
// 在下載大文件之前,需要獲得文件信息之后,由用戶做出判斷之后在再下載.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"HEAD";
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {        
        //需要下載的文件長度:
        long long serverFileLength = response.expectedContentLength;
}

4.NSFileManager

  1. NSFileManager 主要對文件進行管理, 具有:創建文件,復制文件,刪除文件,剪切文件的功能。
  2. NSFileManager 為單例,不能用 alloc 創建:
//創建 NSFileManager 對象
NSFileManager *fileManager = [NSFileManager defaultManager];

  1. 常用方法:
//創建一個?件并寫入數據
- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;
//從?個文件中讀取數據
- (NSData *)contentsAtPath:(NSString *)path;
//srcPath路徑上的?件移動到 dstPath 路徑上, 注意這里的路徑是?件路徑?不是目錄
- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;
//srcPath路徑上的文件復制到 dstPath 路徑上
- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;
//文件是否存在
- (BOOL)fileExistsAtPath:(NSString *)path;
// 移除?件
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error;

  1. 創建文件:
//創建 NSFileManager 對象
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *homePath = NSHomeDirectory();
NSString *path = [homePath stringByAppendingPathComponent:@"file.txt"];
NSString *text = @"docoder";
//將字符串轉成NSData類型
NSData *data = 1;
//寫?文件
BOOL success = [fileManager createFileAtPath:path contents:data attributes:nil];

  1. 讀取文件
//創建 NSFileManager 對象
NSFileManager *fileManager = [NSFileManager defaultManager];
//根據路徑讀取文件
NSData *fileData = [fileManager contentsAtPath:filePath];
//將NSData轉NSString
NSString *content = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
  1. 剪切、復制

NSString *homePath = NSHomeDirectory();
//源?件路徑
NSString *srcPath = [homePath stringByAppendingPathComponent:@"file.txt"];
//目標路徑
NSString *toPath = [homePath stringByAppendingPathComponent:@"Documents/file.txt"];


  NSError *error;
  //剪切(移動)文件
  //將srcPath路徑的文件剪切(移動)到toPath路徑
  BOOL isSuccess = [fm moveItemAtPath:srcPath toPath:toPath error:&error];
  if(!isSuccess){
      NSLog(@"失?。?@",error);
  }
  //復制文件
  //將srcPath路徑的?件復制到toPath路徑
  BOOL success = [fm copyItemAtPath:srcPath toPath:toPath error:nil];
    
  1. 刪除文件
//判斷?件是否存在
BOOL isExist = [fm fileExistsAtPath: path];
if (isExist) {
  //刪除?件
  BOOL success = [fm removeItemAtPath:path error:nil];
  if (success) {
      NSLog(@"remove success");
  }
}

8.獲取文件大小

1. 通過讀取文件屬性獲得:
NSFileManager *fileManager = [NSFileManager defaultManager];
//獲得文件的屬性字典
NSDictionary *attrDic = [fileManager attributesOfItemAtPath:path error:nil];
//獲取?件?小
NSNumber *fileSize = [attrDic objectForKey:NSFileSize];

2. 計算獲得 (此方法如果讀取大文件會很占有內存,不建議使用):
NSFileManager *fileManager = [NSFileManager defaultManager];
NSData *data = [fileManager contentsAtPath:path];
NSInteger len=data.length;


9.斷點續傳

  • 設置請求頭信息(User-Agent; Content-Type ;Range)

  • Range: 告訴服務器,本次請求(想要獲得的數據)從哪里開始,取多少數據...

  • 設置 Range 頭信息:

    1. Bytes=x-y: 從第x個字節開始,下載y個字節!
    2. Bytes=0- : 從第0個字節開始,下載到結束!
    3. Bytes=x- :從第x個字節開始,下載結束!
  • 斷點續傳格式
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 設置斷點續傳信息
    NSString *range = [NSString stringWithFormat:@"Bytes=%lld-%lld",startSize,endSize];
    [request setValue:range forHTTPHeaderField:@"Range"];
    
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容