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 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" : @,
@"appType" : @,
@"slotId" : @"",
@"width" : @,
@"height" : @,
@"creativeType": @,
@"minCpm" : @
};
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:dict1 options: 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提供了与断点下载相关的几个方法:

// 使用这种方式取消下载可以得到将来用来恢复的数据,保存起来
[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 = ;
// 是否允许使用蜂窝网络(后台传输不适用)
config.allowsCellularAccess = YES;
// 还有很多可以设置的属性

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

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

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

除了支持任务的暂停和断点续传,我觉得NSURLSession之于NSURLConnection的最伟大的进步就是支持后台上传下载任务,这又是一个可以深入讨论的话题.但在这方面我还没有进行深入的研究,待后续了解之后另行开贴.

NSURLConnection 代理方法

    NSString * urlStrEcode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlStr]];
NSURL * url = [NSURL URLWithString:urlStr];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
[request setTimeoutInterval:]; 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回调方法

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:];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { }];

NSURLSession、NSURLConnection的更多相关文章

  1. NSURLSession 和 NSURLConnection 的比较

    一.NSURLConnection 1.iOS2.0出现,iOS9.0后废弃的网络请求发送方式 2.可以在初始化时确定发送同步还是异步的请求,并且可以选择执行队列. +(void)sendAsynch ...

  2. NSURLSession与NSURLConnection区别

    1. 使用现状      NSURLSession是NSURLConnection 的替代者,在2013年苹果全球开发者大会(WWDC2013)随ios7一起发布,是对NSURLConnection进 ...

  3. iOS边练边学--NSURLSession、NSURLSessionTask的介绍与使用以及url中包含了中文的处理方法

    一.NSURLSession.NSURLSessionTask的使用步骤 首先创建NSURLSession对象 通过NSURLSession对象创建对应的任务 <1>NSURLSessio ...

  4. iOS NSURLSession VS NSURLConnection

    NSURLSession VS NSURLConnection NSURLSession可以看做是NSURLConnection的进化版,其对NSURLConnection的改进点有: * 根据每个S ...

  5. NSURLSession/NSURLConnection的上传文件方法(已做了更新)

    最好的学习方法就是 领悟 + 证悟. 此篇文章的理论基础主要是与HTTP网络通信协议相关.为集中精力,可以先把TCP/IP协议这些置之不理,也就是先只关注HTTP的请求和响应的结构.HTTP完整的原理 ...

  6. NSURLSession和NSURLConnection

    iOS9.0之后NSURLConnection被注销,采用NSURLSession,先介绍NSURLSession,然后介绍NSURLConnection 1.NSURLSession: post请求 ...

  7. 从nsurlsession、Alamofire到moya

    更好的理解(抽象).更少的构建(配置).更方便的表达(语言) 一.iOS系统的网络编程(DSL概念) ios缺省的网络编程只是给出了网络编程的基本概念: urlsession.request.resp ...

  8. iOS网络4——Reachability检测网络状态

    一.整体介绍 前面已经介绍了网络访问的NSURLSession.NSURLConnection,还有网页加载有关的webview,基本满足通常的网络相关的开发. 其实在网络开发中还有比较常用的就是网络 ...

  9. iOS 支持 IPv6

    苹果的规定:2016年6月1日提交到App Store必须支持IPv6-only网络. 官方文档:https://developer.apple.com/library/mac/documentati ...

随机推荐

  1. onAttachedToWindow () 和 onDetachedFromWindow () ; 以及更新视图的函数ondraw() 和dispatchdraw()的区别

    protected void onAttachedToWindow() This is called when the view is attached to a window. At this po ...

  2. MVC的EF编辑,不用查询直接修改

    EF中会为每个 管理的 实体对象 创建一个代理包装类对象,其中会跟踪 实体对象 的状态和每个属性的状态: 一.通常使用EF更新的方式,先查询出要修改的数据,然后再修改新的值:实体对象被修改的属性 在 ...

  3. devexpress 中Grid 的使用:为零不显示

    如果要让为0的列不显示: this.gridColumn_FAmount.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric; ...

  4. PHP与MySQL动态网站开发1

    PHP内嵌在HTML中,置于 <?php ?> 标签内 一般php文件扩展名.php 在body结算标签之前 对于远程服务器,可以用ftp工具传程序 打印语句 echo'Hello Wor ...

  5. [转]各种字符串Hash函数比较

    转自:https://www.byvoid.com/zht/blog/string-hash-compare 常用的字符串Hash函数还有ELFHash,APHash等等,都是十分简单有效的方法.这些 ...

  6. Lodop Web打印插件使用

    <object id="LODOP_OB" classid="clsid:2105C259-1E0C-4534-8141-A753534CB4CA" st ...

  7. AlertDialog

    1.AlertDialog点击时不自动消失 //在setPositiveButton和setNegativeButton根据自己的逻辑处理,大概代码如下 if(validate){//验证通过自动消失 ...

  8. hdoj 1859 最小长方形

    最小长方形 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submi ...

  9. 转载ASP.NET MVC 中@Html.Partial,@Html.Action,@Html.RenderPartial,@Html.RenderAction区别

    对这四个的区别做一个总结,清理一下思路,方便以后使用: 1.带有Render的方法返回值是void,在方法内部进行输出:不带的返回值类型为MvcHtmlString,所以只能这样使用:     @Ht ...

  10. C语言/C++中怎样产生随机数

    C语言/C++怎样产生随机数:这里要用到的是rand()函数, srand()函数,和time()函数. 需要说明的是,iostream头文件中就有srand函数的定义,不需要再额外引入stdlib. ...