iOS之網上下載資料的兩種方式

夢筆隨心發表於2016-05-17

//

//  ViewController.m

//  檔案下載

//

//  Created by zj on 16/5/17.

//  Copyright © 2016 zj. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()<NSURLSessionDownloadDelegate>


@end


@implementation ViewController

使用前記得在info.plist裡面匯入網路協議

在此我使用的url是我本地的伺服器  大家可以使用網上的介面下載嘗試

/*

 使用block方式下載資料 適合下載小檔案 不能監聽下載過程

- (void)viewDidLoad {

    [super viewDidLoad];

  NSString *str = @"http://127.0.0.1/設計模式解析.pdf";

    str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSURL *url = [NSURL URLWithString:str];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    NSURLSession *session = [NSURLSession sharedSession];

    建立下載會話任務

    NSURLSessionDownloadTask *downLoadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        拼接檔案路徑,用來存放我們下載好的檔案

        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:response.suggestedFilename];

        將返回的location轉化成路徑格式

        NSString *temPath = [location path];

        準備二進位制資料

        NSData *data = [NSData dataWithContentsOfFile:temPath];

        建立檔案處理物件

        NSFileManager *fileManage = [NSFileManager defaultManager];

        把下載好的檔案寫入到我們準備好的地址裡去

        [fileManage createFileAtPath:path contents:data attributes:nil];

        

    }];

     開始下載任務

    [downLoadTask resume];

}

*/


-(void)viewDidLoad{

    [super viewDidLoad];

    //使用代理方式來下載檔案  一般用來下載大一點的檔案 可以監聽下載過程

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/Office4mac.dmg"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]] ;

    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request];

    [downloadTask resume];

}

//監聽下載的代理方法 

//下載完成時呼叫

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask

didFinishDownloadingToURL:(NSURL *)location{

    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"user.mmm"];

        NSString *temPath = [location path];

           NSData *data = [NSData dataWithContentsOfFile:temPath];

            NSFileManager *fileManage = [NSFileManager defaultManager];

            [fileManage createFileAtPath:path contents:data attributes:nil];

    

}

//下載過程呼叫

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask

      didWriteData:(int64_t)bytesWritten

 totalBytesWritten:(int64_t)totalBytesWritten

totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{

      NSLog(@"這次共下載=%lld 當前下載總數= %lld  期待下載的總數%lld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);

}



- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


相關文章