NSURLSession、NSURLConnection

NSURLSesstion GET方法  block回调方法
NSString * urlStr = @"http://192.168.1.247:8100/stream?cname=cha_26&seq=0&token=xxx"; NSURLSession * session = [NSURLSession sharedSession]; NSURLSessionTask * sessionTask = [session dataTaskWithURL:urlStr completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@""); }]; [sessionTask resume];

NSURLSesstion POST方法 block回调方法缓存

NSURL * url = [NSURL URLWithString:@"http://www.daka.com/login"];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"username=daka&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSession * session = [NSURLSession sharedSession];
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"");
    }];
    [task resume];

 NSURLSesstion 代理方法服务器

NSURLSessionDataDelegate代理方法

 NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    NSURLSessionDataTask * task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.daka.com/login?userName=daka&pwd=123"]]];
    [task resume];
// 1.接收到服务器的响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    // 容许处理服务器的响应,才会继续接收服务器返回的数据
    completionHandler(NSURLSessionResponseAllow);
}

// 2.接收到服务器的数据(可能调用屡次)
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    // 处理每次接收的数据
}

// 3.请求成功或者失败(若是失败,error有值)
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    // 请求完成,成功或者失败的处理
}

 

AFHttpSessionManager GET 请求网络

AFHTTPSessionManager * session = [AFHTTPSessionManager manager];
    session.requestSerializer.timeoutInterval = 5.0f;
    [session GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"downloadProgress");
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"失败");
        NSLog(@"error:%@",error);
        switch (error.code) {
            case AFNetworkErrorType_NoNetwork :
                NSLog(@"网络连接失败,请检查网络。");
                break;
            case AFNetworkErrorType_TimedOut :
                NSLog(@"访问服务器超时,请检查网络。");
                break;
            case AFNetworkErrorType_3840Failed :
                NSLog(@"服务器报错了,请稍后再访问。");
                break;
            default:
                break;
        }
    }];

AFHttpSessionManager POST 请求session

    [session POST:urlStr parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"downloadProgress");
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败");
        NSLog(@"error:%@",error);
    }];

 

    NSURL * url = [NSURL URLWithString:@"http://192.168.101.101:8080/DSPManager/bidding/ssp/process"];
    
    NSURLSession * session = [NSURLSession sharedSession];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"bid=aaa&platform=1&appType=1&slotId=222&width=273&height=230&creativeType=0&minCpm=2000" dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (!error) {
            NSLog(@"response--->%@",response);
            NSLog(@"data--->%@",data);
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"dic--->%@",dict);
        }else{
            NSLog(@"error--->%@",error);
        }
    }];
    [task resume];

 

    NSURL * url = [NSURL URLWithString:@"http://192.168.101.101:8080/DSPManager/bidding/ssp/process"];
    
    NSURLSession * session = [NSURLSession sharedSession];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
//    request.HTTPBody = [@"bid=aaa&platform=1&appType=1&slotId=222&width=273&height=230&creativeType=0&minCpm=2000" dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * dict1 = @{
                            @"bid"         : @"fengmin",
                            @"platform"    : @1,
                            @"appType"     : @1,
                            @"slotId"      : @"222",
                            @"width"       : @273,
                            @"height"      : @230,
                            @"creativeType": @0,
                            @"minCpm"      : @2000
                           };
    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:dict1 options:0 error:NULL];
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (!error) {
            NSLog(@"response--->%@",response);
            NSLog(@"data--->%@",data);
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"dic--->%@",dict);
        }else{
            NSLog(@"error--->%@",error);
        }
    }];
    [task resume];

 

NSURLSessionDownloadTask

NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@"http://www.daka.com/resources/image/icon.png"] ;
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    // location是沙盒中tmp文件夹下的一个临时url,文件下载后会存到这个位置,因为tmp中的文件随时可能被删除,因此咱们须要本身须要把下载的文件挪到须要的地方
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
    // 剪切文件
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:path] error:nil];
}];
    // 启动任务
    [task resume];

NSURLSessionDownloadDelegate代理方法

// 每次写入调用(会调用屡次)
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
// 可在这里经过已写入的长度和总长度算出下载进度
CGFloat progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite; NSLog(@"%f",progress);
}

// 下载完成调用
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didFinishDownloadingToURL:(NSURL *)location {
    // location仍是一个临时路径,须要本身挪到须要的路径(caches下面)
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:nil];
}

// 任务完成调用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {

}

NSURLSessionUploadTask

NSURLSessionUploadTask *task =
[[NSURLSession sharedSession] uploadTaskWithRequest:request
                                           fromFile:fileName
                                  completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
 [self.session uploadTaskWithRequest:request
                            fromData:body
                   completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
 NSLog(@"-------%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
 }];

断点下载

NSURLSessionDownloadTask提供了与断点下载相关的几个方法:app

// 使用这种方式取消下载能够获得未来用来恢复的数据,保存起来
[self.task cancelByProducingResumeData:^(NSData *resumeData) {
    self.resumeData = resumeData;
}];

// 因为下载失败致使的下载中断会进入此协议方法,也能够获得用来恢复的数据
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    // 保存恢复数据
    self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
}

// 恢复下载时接过保存的恢复数据
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
// 启动任务
[self.task resume];
- (void)suspend;//让当前的任务暂停
- (void)resume;//能够启动任务,还能够唤醒suspend状态的任务
- (void)cancel;//取消当前的任务,你也能够向处于suspend状态的任务发送cancel消息,任务若是被取消便不能再恢复到以前的状态.

NSURLSessionConfiguration

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
// 超时时间
config.timeoutIntervalForRequest = 10;
// 是否容许使用蜂窝网络(后台传输不适用)
config.allowsCellularAccess = YES;
// 还有不少能够设置的属性

有没有发现咱们使用的Configuration都是默认配置:[NSURLSessionConfiguration defaultSessionConfiguration],其实它的配置有三种类型:ide

+ (NSURLSessionConfiguration *)defaultSessionConfiguration;
+ (NSURLSessionConfiguration *)ephemeralSessionConfiguration;
+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier

表示了NSURLSession几种不一样的工做模式.
默认的配置会将缓存存储在磁盘上,第二种瞬时会话模式不会建立持久性存储的缓存,第三种后台会话模式容许程序在后台进行上传下载工做.url

除了支持任务的暂停和断点续传,我以为NSURLSession之于NSURLConnection的最伟大的进步就是支持后台上传下载任务,这又是一个能够深刻讨论的话题.但在这方面我尚未进行深刻的研究,待后续了解以后另行开贴.spa

 

NSURLConnection 代理方法代理

    NSString * urlStrEcode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlStr]];
    NSURL * url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    [request setTimeoutInterval:10];
    
    NSURLConnection * conn = [NSURLConnection connectionWithRequest:request delegate:self];
    [conn start];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"response:%@",response);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"data:%@",data);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
     NSLog(@"connection:%@",connection);
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error:%@",error);
}

NSURLConnection block回调方法code

NSString * urlStr = @"http://192.168.1.247:8100/stream?cname=cha_26&seq=0&token=xxx";
    NSString * urlStrEcode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlStr]];
    NSURL * url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    [request setTimeoutInterval:10];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
    }];
相关文章
相关标签/搜索