iOS--NSURLSession请求总结

#define WCYCacheFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@""]


#import "ReviewViewController.h"


@interface ReviewViewController ()<NSURLSessionDataDelegate>


@property(nonatomic,strong)NSURLSession *session;


@property(nonatomic,strong)NSURLSessionDataTask *task;

// 写文件数据流的对象

@property(nonatomic,assign) NSOutputStream *stream;

//文件的总长度

@property(nonatomic,assign)NSInteger contentLength;


@end


@implementation ReviewViewController


-(NSURLSession *)session{

        if (_session == nil) {

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

        }

        return _session;

}


-(NSOutputStream *)stream{

        if (_stream == nil) {

                

                _stream = [NSOutputStream outputStreamToFileAtPath:WCYCacheFile append:YES];

        }

        return _stream;

}


- (void)viewDidLoad {

    [super viewDidLoad];

        

        NSString *urlStr = @"www.baidu.com";

        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        NSURL *url = [NSURL URLWithString:urlStr];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

        request.HTTPMethod = @"POST";

        request.HTTPBody = [@"123" dataUsingEncoding:NSUTF8StringEncoding];

        

        NSURLSessionDataTask *task = [[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

                

        }];

        

        [task resume];

        

        

        NSURLSessionDownloadTask *taskDownload = [[NSURLSession sharedSession]downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

                //小文件下载。

        }];

        [taskDownload resume];

        

        

        //断点下载

        self.task = [self.session dataTaskWithURL:[NSURL URLWithString:@""]];

        [self.task resume];

        

        

        //文件上传

        NSURLSessionDataTask *taskUpload = [[NSURLSession sharedSession]uploadTaskWithRequest:request fromData:nil completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

                

        }];

        [taskUpload resume];

    // Do any additional setup after loading the view.

}


//1. 接收到响应

-(void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSHTTPURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler{

        

        //打开流

        [self.stream open];

        

        //获得文件的总长度

        self.contentLength = [response.allHeaderFields[@"Content-Length"]integerValue];

        

        

        //接受这个请求,允许接受服务器的数据。

        completionHandler(NSURLSessionResponseAllow);

        

        

        

}

//2.接收到服务器返回的数据,这个方法会被调用N次。

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{

        

        //写入数据。

        [self.stream write:data.bytes maxLength:data.length];

        

        //目前的下载长in

       NSInteger downloadLength = [[[NSFileManager defaultManager]attributesOfItemAtPath:WCYCacheFile error:nil][NSFileSize] integerValue];

        

        //得到下载进度

        NSLog(@"%f",1.0 * downloadLength/self.contentLength);

        

}


//3.请求完毕,成功/失败

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{

        

        //关闭流

        [self.stream close];

        self.stream = nil;

        

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值