NSURLSession

NSURLSession

NSURLSessionTask : 任务的基类,包括

  1. NSURLSessionDataTask : 缓存到内存中的任务,一般是网络请求等不需要永久存储的
  2. NSURLSessionUploadTask : 上传数据的任务(属于Data层次)
  3. NSURLSessionDownloadTask : 下载数据到本地磁盘的任务

tableviewcell最外层一定是数组

下载任务(需要代理)

@property (weak, nonatomic) IBOutlet UIImageView *imageV;
@property (weak, nonatomic) IBOutlet UIProgressView *progressV;
@property (weak, nonatomic) IBOutlet UILabel *progressT;
@property (nonatomic,strong) NSData *resumeData;
@property (nonatomic,strong) NSURLSessionDownloadTask *resumeDLTask;
@property (nonatomic,strong) NSURLSession *session;

//当有数据的时候,继续原来的加载
    if (_resumeData) {
        _resumeDLTask = [_session downloadTaskWithResumeData:_resumeData];
    }else{//当没有数据的时候,重新开始加载
//获取一个url
    NSURL *imageUrl = [NSURL URLWithString:@"http://image.tianjimedia.com/uploadImages/2011/314/6328K77VW824.jpg"];
    //根据url创建一个GET请求
    NSURLRequest *request = [NSURLRequest requestWithURL:imageUrl];
    //用默认配置设置一个session对象
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]delegate:self delegateQueue:nil];
    //用session对象和GET请求创建一个DownLoadTask
    _resumeDLTask = [session downloadTaskWithRequest:request];
    }
    //启动下载任务
    [_resumeDLTask resume];
}  

- (IBAction)stopDownload:(UIButton *)sender {
    //暂停下载任务 方法:cancelByProducingResumeData,把下载的部分给 _resumeData 保存起来
    [_resumeDLTask cancelByProducingResumeData:^(NSData *resumeData) {
        _resumeData = resumeData;

        _resumeDLTask = nil;
    }];
}

//下载的过程中调用
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
     didWriteData:(int64_t)bytesWritten//每次写入的字节数
totalBytesWritten:(int64_t)totalBytesWritten//当前一共写入多少字节
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite//文件大小
{
    NSLog(@"loading....");
    double progress = totalBytesWritten / totalBytesExpectedToWrite;
    //更新进度.主线程
    dispatch_async(dispatch_get_main_queue(), ^{
        _progressV.progress = progress;
        _progressT.text = [NSString stringWithFormat:@"%.2f%%",progress * 100];
    });
}

//下载完成后调用
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    NSLog(@"fished....");
    NSLog(@"location >> %@",location);
    //创建文件管理器
    NSFileManager *fileManger = [NSFileManager defaultManager];
    //访问沙盒路径,只有这一种方法允许访问沙盒,第一个参数是要访问的字典对象,第二个参数是是NSSearchDomainMask枚举值
    NSURL *docUrl = [fileManger URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0];
    NSError *error;
    //每一个斜杠代表一个 Component ,用默认路径下的最后的一个Component 取出文件
    NSURL *saveUrl = [docUrl URLByAppendingPathComponent:[location lastPathComponent]];
    //先判断这个路径下有没有文件,如果有,先删除
    if ([fileManger fileExistsAtPath:[saveUrl path]]) {
        [fileManger removeItemAtURL:saveUrl error:&error];
        if (error) {
            NSLog(@"error");
            return;
        }
    }
    //从临时目录中把文件移到docments文件夹
    if ([fileManger moveItemAtURL:location toURL:saveUrl error:&error]) {
        if (error) {
            NSLog(@"error >> %@",error);
            return;
        }
    //绘制界面是主线程做的
    dispatch_async(dispatch_get_main_queue(), ^{
            _progressV.progress = 1;
            _imageV.image = [UIImage imageWithContentsOfFile:[saveUrl path]];
        });
    }
}

配置文件的三种模式:

  1. default:默认模式
  2. 瞬时模式,把请求到的数据放到内存中
  3. 后台模式:大型的游戏

NSURLConnection(9.0之后不能用,不推荐使用)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值