天天看點

iOS之網絡下載下傳檔案

檔案下載下傳

檔案下載下傳在我們日常開發中經常使用到,比如:圖檔,音頻,視訊等
簡單的小檔案下載下傳
  • get異步下載下傳
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *urlStr =  @"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1560231628392&di=1ea41537c16f8045d212ef09b24746cc&imgtype=0&src=http%3A%2F%2Fg.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2F7acb0a46f21fbe094542faa760600c338744ad60.jpg";
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //建立請求
    NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    //建立一個線程
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    [NSURLConnection sendAsynchronousRequest:requst queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        //data是下載下傳的資料
         UIImage *image = [UIImage imageWithData:data];
        //回到主線程
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            self.imageView.image = image;
        }];
        
        
    }];
 
 
    
}
           
iOS之網絡下載下傳檔案
  • 代理方法 監聽就現在

    用本地伺服器下載下傳一個短視訊

    本地伺服器的搭建

    可以點選這裡檢視
//懶加載 屬性
- (NSMutableData *)finData {
    if (!_finData) {
        _finData = [NSMutableData data];
    }
    return _finData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *urlStr =  @"http://localhost/video.mp4";
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //建立請求
    NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    
    //設定代理 遵循協定
    [[NSURLConnection alloc] initWithRequest:requst delegate:self];
 
}


//收到響應
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    //擷取到 總資料的大小
    self.totalLength = response.expectedContentLength;
    
    
}

//接受資料
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    //拼接資料
    [self.finData appendData:data];
    //計算下載下傳
    NSLog(@"%f",  1.0 *self.finData.length/self.totalLength);
    
}

//失敗的時候
- (void)connection:(NSURLConnection *)connection didFailWithError:(nonnull NSError *)error{
    
}

//加載完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//    NSLog(@"完成---%@",self.finData);
    self.finData = nil;
}



           
iOS之網絡下載下傳檔案

大檔案下載下傳

  • NSFileManager

    點選這裡檢視
  • NSFileHandle

    檔案句柄 指針 ,

    注意

    :在不用這個對象執行個體的時候,一定要

    關閉

iOS之網絡下載下傳檔案
當大檔案在 下載下傳的時候,我們需要用到

NSFileHandle

指針類指向,接受檔案的資料拼接成一個完成的

資料

,當然我們也需要

NSFileManager

建立一個

空檔案

來存儲接受的資料
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *urlStr =  @"http://localhost/video.mp4";
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //建立請求
    NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    
    [[NSURLConnection alloc] initWithRequest:requst delegate:self];
 
 
    
}

//收到響應
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    self.totalLength = response.expectedContentLength;
    
    //擷取檔案路徑
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    self.fullpath = [cachePath stringByAppendingPathComponent:@"123.mp4"];
    
    //建立一個空檔案
    
    [[NSFileManager defaultManager] createFileAtPath:self.fullpath  contents:nil attributes:nil];
    
    //建立檔案指針
    self.handle = [NSFileHandle fileHandleForWritingAtPath:self.fullpath];
    
    
    
}

//接受資料
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
   
    
    self.currentLegth += data.length;
    
    //接受到資料時 将指針 移動資料的末尾
    [self.handle seekToEndOfFile];
    
    //寫入檔案
    [self.handle writeData:data];
    
    NSLog(@"%f",1.0 * self.currentLegth/self.totalLength);
    
    
}

//失敗的時候
- (void)connection:(NSURLConnection *)connection didFailWithError:(nonnull NSError *)error{
    
}

//加載完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

    //下載下傳完成關閉 指針
    [self.handle closeFile];
    self.handle = nil;
}



           

斷點下載下傳

  • 主要是設定

    請求頭

    的内容
  • 原理:根據目前下載下傳檔案的大小(記錄),設定到

    請求頭

    再次下載下傳的時候,從目前記錄的位置開始下載下傳
///開始下載下傳
- (IBAction)handleStartAction:(UIButton *)sender {
    NSString *urlStr =  @"http://localhost/video.mp4";
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //建立請求
    NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    //設定請求頭
    //從目前在下在檔案的大小 開始下載下傳 self.currentLegth 記錄之前下載下傳的位置
    NSString *rangeByte = [NSString stringWithFormat:@"bytes=%zd-",self.currentLegth];
    
    [requst setValue:rangeByte forHTTPHeaderField:@"Range"];
    
  self.connection  = [[NSURLConnection alloc] initWithRequest:requst delegate:self];
    
}

///取消i下載下傳

- (IBAction)handleCancleAction:(UIButton *)sender {
   
    [self.connection cancel];
    
}


//收到響應
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    //再次下載下傳的時候,如果已經存在了,就直接return,從記錄的位置下載下傳
    if (self.currentLegth > 0) {
        
        return;
    }
    
    self.totalLength = response.expectedContentLength;
    
    //擷取檔案路徑
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    self.fullpath = [cachePath stringByAppendingPathComponent:@"123.mp4"];
    
    //建立一個空檔案
    
    [[NSFileManager defaultManager] createFileAtPath:self.fullpath  contents:nil attributes:nil];
    
    //建立檔案指針
    self.handle = [NSFileHandle fileHandleForWritingAtPath:self.fullpath];
    
    
    
    
}

//接受資料
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    
    self.currentLegth += data.length;
   
    
    //接受到資料時 将指針 移動資料的末尾
    [self.handle seekToEndOfFile];
    
    //寫入檔案
    [self.handle writeData:data];
    
    self.proviessView.progress = 1.0 * self.currentLegth/self.totalLength;
    
    NSLog(@"%f",1.0 * self.currentLegth/self.totalLength);
    
    
}

//失敗的時候
- (void)connection:(NSURLConnection *)connection didFailWithError:(nonnull NSError *)error{
    
}

//加載完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    //下載下傳完成關閉 指針
    [self.handle closeFile];
    self.handle = nil;
}

           
iOS之網絡下載下傳檔案