從網上DownLoad

來源:互聯網
上載者:User

標籤:

方法步驟一、storyboard布局

 

#import "ViewController.h"@interface ViewController ()<NSURLSessionDownloadDelegate>///顯示圖片的@property (weak, nonatomic) IBOutlet UIImageView *imageView;///顯示進度的@property (weak, nonatomic) IBOutlet UIProgressView *progressView;///下載任務的屬性@property (nonatomic,strong)NSURLSessionDownloadTask *task;///網路請求類@property (nonatomic,strong)NSURLSession *session;///發送請求類@property (nonatomic,strong)NSURLRequest *request;///用於儲存已經下載的資料的,供繼續下載使用@property(nonatomic,strong)NSMutableData *data;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    self.progressView.progress = 0  ;   }- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}#pragma mark - 開始下載- (IBAction)startButton:(id)sender {    NSString *urlStr = @"http://f.hiphotos.baidu.com/zhidao/wh%3D450%2C600/sign=2b7d8fd27fd98d1076810435140f9438/503d269759ee3d6d505b9ee540166d224f4ade7a.jpg";    NSURL *url = [NSURL URLWithString:urlStr];        self.request = [NSURLRequest requestWithURL:url];    //建立NSURLSession    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];    //網路請求    self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:([NSOperationQueue mainQueue])];    //下載請求任務    self.task = [self.session downloadTaskWithRequest:self.request];        //開啟    [self.task resume];        }#pragma mark - 暫停下載- (IBAction)pauseButton:(id)sender {    //暫停    if (self.task) {        //暫停並儲存之前已經下載的內容        __weak typeof(self)weakSelf = self;        [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {            weakSelf.data = [NSMutableData data];        }];    }    [self.task suspend];}#pragma mark - 繼續下載- (IBAction)continueButton:(id)sender {    //哦按段當前任務是否存在,是發送請求還是處理資料        if (self.task!=nil) {        //說明已經下載,這裡要處理的就是資料        self.task = [self.session downloadTaskWithResumeData:self.data];    }else {        //此時沒有下載任何內容,應該重新發送求求進行下載        self.task = [self.session downloadTaskWithRequest:self.request];    }    //啟動    [self.task resume];    }#pragma mark - 代理方法//下載完成走的方法- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {    //找到檔案夾管理器        NSFileManager *fileManager = [NSFileManager defaultManager];        //先找到沙箱    NSArray *urlArray = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];        //根據沙箱路徑擷取Document路徑        NSURL *url = [urlArray objectAtIndex:0];    NSLog(@"url=====%@",url);    //    response.suggestedFilename:建議使用的檔案名稱,一般根服務端的檔案名稱一致        NSURL *saveUrl = [url URLByAppendingPathComponent:downloadTask.response.suggestedFilename];        NSLog(@"sabrUrl -------%@",saveUrl);    //location:臨時檔案的路徑(下載好的檔案)    //AtPath:剪下前的檔案路徑 //ToPath:剪下後的檔案路徑    [fileManager moveItemAtPath:location.path toPath:saveUrl.path error:nil];    self.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:saveUrl]];  }#pragma mark - 下載完,部分就會調用(可能被調用多次)- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {        //下載當前段的資料    NSLog(@"bytesWrite = %lld",bytesWritten);    NSLog(@"totalytesWritten = %lld",totalBytesWritten);    NSLog(@"titalBytesExpectedToWrite = %lld",totalBytesExpectedToWrite);                self.progressView.progress = (CGFloat)totalBytesWritten /(CGFloat)totalBytesExpectedToWrite;            NSLog(@"%f",self.progressView.progress);}@end

從網上DownLoad

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.