iOS--NSURLSession请求总结

来源:互联网 发布:java web项目多线程 编辑:程序博客网 时间:2024/06/16 12:49

#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 = [NSURLSessionsessionWithConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration] delegate:selfdelegateQueue:[[NSOperationQueuealloc]init] ];

        }

        return _session;

}


-(NSOutputStream *)stream{

        if (_stream ==nil) {

                

                _stream = [NSOutputStreamoutputStreamToFileAtPath:WCYCacheFileappend:YES];

        }

        return _stream;

}


- (void)viewDidLoad {

    [superviewDidLoad];

        

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

        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        NSURL *url = [NSURLURLWithString:urlStr];

        NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];

        request.HTTPMethod = @"POST";

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

        

        NSURLSessionDataTask *task = [[NSURLSessionsharedSession]dataTaskWithRequest:requestcompletionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) {

                

        }];

        

        [task resume];

        

        

        NSURLSessionDownloadTask *taskDownload = [[NSURLSessionsharedSession]downloadTaskWithRequest:requestcompletionHandler:^(NSURL *_Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

                //小文件下载。

        }];

        [taskDownload resume];

        

        

        //断点下载

        self.task = [self.sessiondataTaskWithURL:[NSURLURLWithString:@""]];

        [self.taskresume];

        

        

        //文件上传

        NSURLSessionDataTask *taskUpload = [[NSURLSessionsharedSession]uploadTaskWithRequest:requestfromData:nilcompletionHandler:^(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:(nonnullNSURLSessionDataTask *)dataTask didReceiveResponse:(nonnullNSHTTPURLResponse *)response completionHandler:(nonnullvoid (^)(NSURLSessionResponseDisposition))completionHandler{

        

        //打开流

        [self.streamopen];

        

        //获得文件的总长度

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

        

        

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

        completionHandler(NSURLSessionResponseAllow);

        

        

        

}

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

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

        

        //写入数据。

        [self.streamwrite:data.bytesmaxLength:data.length];

        

        //目前的下载长in

       NSInteger downloadLength = [[[NSFileManagerdefaultManager]attributesOfItemAtPath:WCYCacheFileerror:nil][NSFileSize]integerValue];

        

        //得到下载进度

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

        

}


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

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

        

        //关闭流

        [self.streamclose];

        self.stream =nil;

        

}


0 0