UI:网络编程2,文件移动,断点续传

来源:互联网 发布:淘宝上买东西如何退货 编辑:程序博客网 时间:2024/05/19 21:41
NSURLSession是iOS7中新的网络接口,如果用户强制将程序关闭,NSURLSession会断掉。
NSURLSession提供的功能:
1.通过URL将数据下载到内存
2.通过URL将数据下载到文件系统
3.将数据上传到指定URL
4.在后台完成上述功能


- (IBAction)startDownload:(id)sender{

   

    NSURL*url = [NSURLURLWithString:@"http://yinyueshiting.baidu.com/data2/music/134368855/124197079111600128.mp3?xcode=ede3a05eff7c66410d9b8f0c677c76d2"];

   

   NSURLSessionConfiguration *config = [NSURLSessionConfigurationdefaultSessionConfiguration];//网络接口的结构师哪种类型

   

   NSURLSession *downloadSession = [NSURLSessionsessionWithConfiguration:config delegate:selfdelegateQueue:[NSOperationQueue mainQueue]];

   

   NSURLSessionDownloadTask *task = [downloadSessiondownloadTaskWithURL:url];

   //网络接口的三个任务分别为下载上传,默认的data

    [taskresume];

   

   

   

   

}



- (void)moveDownloadFile:(NSURL*)sourceFilePath toNewFile:(NSString *)destFilePath {

   

   NSFileManager *manager = [NSFileManagerdefaultManager];//文件操作方式,单例

Documents:苹果建议将程序创建产生的文件以及应用浏览产生的文件数据保存在该目录下,iTunes备份和恢复的时候会包括此目录
Library:存储程序的默认设置或其它状态信息;

Library/Caches:存放缓存文件,保存应用的持久化数据,用于应用升级或者应用关闭后的数据保存,不会被itunes同步,所以为了减少同步的时间,可以考虑将一些比较大的文件而又不需要备份的文件放到这个目录下。

tmp:提供一个即时创建临时文件的地方,但不需要持久化,在应用关闭后,该目录下的数据将删除,也可能系统在程序不运行的时候清除。

   

   //目标路径

   NSString *path = [NSHomeDirectory()stringByAppendingPathComponent:destFilePath];//得到home即这个程序的主目录

   //NSString *p =[NSHomeDirectory()stringByAppendingString:destFilePath];这个方法是需要在documents前面加/的。

    NSURL*toURL = [NSURL fileURLWithPath:path];

   

   NSLog(@"path=%@", path);

   

   [manager moveItemAtURL:sourceFilePath toURL:toURLerror:nil];

   //通过文件管理器将某个文件从A地址复制到b地址。

   

   

   

   

}


#pragma  mark -NSSessionDownloadDelegate


//下载完成调用的协议方法

- (void)URLSession:(NSURLSession *)sessiondownloadTask:(NSURLSessionDownloadTask *)downloadTaskdidFinishDownloadingToURL:(NSURL *)location {

   //location为下载完成后临时文件的路径,此文件在此协议方法完成后会被删除,因此应该由用户来把此文件做额外的保存,保存至目标目录。

   NSLog(@"%@", location);

   

   //把临时文件剪切至目标文件夹 ,第一个地址是下载下来的目标文件夹。第二个地址是添加的文件夹。因为app有3个文件夹,分别是上面的3个,然后再documents文件夹下新建一个文件夹。

    [selfmoveDownloadFile:locationtoNewFile:@"Documents/jack.mp3"];

   

   

}


//接收到下载数据调用的协议方法,此方法可能会被调用多次

- (void)URLSession:(NSURLSession *)sessiondownloadTask:(NSURLSessionDownloadTask *)downloadTaskdidWriteData:(int64_t)bytesWrittentotalBytesWritten:(int64_t)totalBytesWrittentotalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{

   //session是主线程的地址,然后download task有地址也有key和value分别是标志1,及running

    floatprogerss = totalBytesWritten * 1.0 /totalBytesExpectedToWrite;

   //bytesWritten,每次请求体的大小,totalBytesWritten已经下载的大小,totalBytesExpectedToWrite,文件总的大小。

   self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%",progerss * 100];

   self.progressView.progress = progerss;

   

   

}

-----------------------------断点续传--------------------------------

#import"ViewController.h"<</font>NSURLSessionDownloadDelegate>


@interface ViewController () {

   

   NSURLSessionDownloadTask *_downloadTask;

    NSData*_savedData; //用来记录已下载信息,用来恢复后续的下载。

   NSURLSession *_downloadSession;

}


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Doany additional setup after loading the view, typically from anib.

}


- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    //Dispose of any resources that can be recreated.

}


- (IBAction)startDownload:(id)sender{

  

   

    if(_downloadTask == nil) {//如果这个任务还没有创建则创建

       NSURL *url = [NSURLURLWithString:@"http://yinyueshiting.baidu.com/data2/music/134368855/124197079111600128.mp3?xcode=ede3a05eff7c66410d9b8f0c677c76d2"];

       

       NSURLSessionConfiguration*config = [NSURLSessionConfigurationdefaultSessionConfiguration];

       

       _downloadSession =[NSURLSession sessionWithConfiguration:config delegate:selfdelegateQueue:[NSOperationQueue mainQueue]];

       

       _downloadTask =[_downloadSession downloadTaskWithURL:url];

       

       [_downloadTaskresume];

   }

   


   

}


- (IBAction)pauseDownload:(id)sender{

   

    if(_downloadTask && _savedData == nil) {

       if (_downloadTask.state ==NSURLSessionTaskStateRunning) {

          

          //取消下载,不可能再恢复此下载任务。

          //[_downloadTask cancel];

          //[_downloadTask suspend];

          //1-1000 1-500 501-1000

          //调用下面方法可以取消一个下载任务,它的完成block会接收一个NSData的参数,此参数中保存了已下载数据的相关信息。

          [_downloadTaskcancelByProducingResumeData:^(NSData * _Nullable resumeData){

             

              _savedData= resumeData;

             

             //把已经取消的task释放

             _downloadTask = nil;

             

             

          }];

          

       }


   }

   

   

   

   

}


- (IBAction)resumeDownload:(id)sender{

   

    if(_savedData) {

      //继续下载时根据暂停下载时保存的resumeData来创建一个新的下载任务

       _downloadTask =[_downloadSessiondownloadTaskWithResumeData:_savedData];

       

      //创建新的下载任务后,把断点续传保存的数据清空,目的为:避免内存泄露,且方便下一次暂停下载的判断。

       _savedData = nil;

       

       [_downloadTaskresume];

   }

  

   

}



- (void)moveDownloadFile:(NSURL*)sourceFilePath toNewFile:(NSString *)destFilePath {

   

   NSFileManager *manager = [NSFileManager defaultManager];

   

   //目标路径

   NSString *path = [NSHomeDirectory()stringByAppendingPathComponent:destFilePath];

    NSURL*toURL = [NSURL fileURLWithPath:path];

   

   NSLog(@"path=%@", path);

   

   [manager moveItemAtURL:sourceFilePath toURL:toURLerror:nil];

   


}


#pragma  mark -NSSessionDownloadDelegate


//下载完成调用的协议方法

- (void)URLSession:(NSURLSession *)sessiondownloadTask:(NSURLSessionDownloadTask *)downloadTaskdidFinishDownloadingToURL:(NSURL *)location {

   //location为下载完成后临时文件的路径,此文件在此协议方法完成后会被删除,因此应该由用户来把此文件做额外的保存,保存至目标目录。

   NSLog(@"%@", location);

   

   //把临时文件剪切至目标文件夹/Documents/

    [selfmoveDownloadFile:locationtoNewFile:@"Documents/jack.mp3"];


   

   _downloadTask = nil;

   _downloadSession = nil;

   

}


//接收到下载数据调用的协议方法,此方法可能会被调用多次

- (void)URLSession:(NSURLSession *)sessiondownloadTask:(NSURLSessionDownloadTask *)downloadTaskdidWriteData:(int64_t)bytesWrittentotalBytesWritten:(int64_t)totalBytesWrittentotalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{

   NSLog(@"downloadTask:%@", downloadTask);

   

    floatprogerss = totalBytesWritten * 1.0 /totalBytesExpectedToWrite;

   

   self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%",progerss * 100];

   self.progressView.progress = progerss;

   

   

 

}




0 0
原创粉丝点击