网络请求 __ NSURLSession
首先配置into.plist文件
1. 添加 App Transport Security Settings , Type栏自动变为Dictionary
2. 点击左边箭头,使之向下,点击右边加号,添加 Allow Arbitrary Loads (Xcode 7.0之后会默认填充Allow Arbitrary Loads )
3. 将value 改为YSE
-- -- 代码实现 -- --
#import "ViewController.h" //NSURLSessionDataDelegate NSURLSession 获取网络数据的代理协议
@interface ViewController ()<NSURLSessionDataDelegate>
//保存结果的data
@property (nonatomic, strong) NSMutableData *resultData; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)post:(id)sender { NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *dataString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData]; NSURLSessionTask *dataTask = [session dataTaskWithRequest:request]; [dataTask resume]; // NSURLSession *session = [NSURLSession sharedSession];
//
// NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
// NSURL *url = [NSURL URLWithString:urlString];
//
// NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//
// NSString *dataString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
// NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
// [request setHTTPBody:postData];
// [request setHTTPMethod:@"POST"];
//
// NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// if (error == nil) {
// NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
// NSLog(@"dic == %@", dic);
// }
// }];
// [task resume];
}
- (IBAction)get:(id)sender {
// //block 回调的方式
// //使用系统提供的全局的NSURLSession对象, 是一个单例
// NSURLSession *session = [NSURLSession sharedSession];
// NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
// NSURL *url = [NSURL URLWithString:urlString];
// //NSURLSession 是基于任务的, 所以所有的东西都要放到任务里面, NSURLSessionTask就是NSURLSession 的任务执行对象
// NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// if (error == nil) {
// NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
// NSLog(@"dic == %@", dic);
// }
// }];
// //NSURLSession的所有任务默认是挂起的, 所以一定要调用resume方法, 让任务开始
// [task resume]; //NSURLSession 代理的异步操作 //NSURLSession 代理人的属性是只读的
// 参数一 : 会话模式
// 参数二 : 代理人
// 参数三 : 代理方法在哪个线程中进行
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"]; //NSURLSessionTask的子类
NSURLSessionTask *dataTask = [session dataTaskWithURL:url]; [dataTask resume]; } - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
//NSURLSession的代理协议里面 必须设置允许继续请求, 才会继续的响应服务器, 获取到数据
completionHandler(NSURLSessionResponseAllow);
self.resultData = [NSMutableData data];
} //接收到数据
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
[self.resultData appendData:data];
} //结束响应
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
if (error == nil) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"dic == %@", dic);
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end
网络请求 __ NSURLSession的更多相关文章
- IOS网络请求之NSURLSession使用
前言: 无论是Android还是ios都离不开与服务器交互,这就必须用到网络请求,记得在2013年做iOS的时候那时候用的ASIHTTPRequest框架,现在重新捡起iOS的时候ASIHTTPReq ...
- NSURLSession网络请求
个人感觉在网上很难找到很简单的网络请求.或许是我才疏学浅 , 所有就有了下面这一段 , 虽然都是代码 , 但是全有注释 . //1/获取文件访问路径 NSString *path=@"ht ...
- iOS - NSURLSession 网络请求
前言 NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0) @interface NSURLSession : NSObject @available(iOS ...
- 介绍NSURLSession网络请求套件
昨天翻译了一篇<NSURLSession的使用>的文章,地址:http://www.cnblogs.com/JackieHoo/p/4995733.html,原文是来自苹果官方介绍NSUR ...
- iOS 网络请求NSURLSession
iOS 7 和 Mac OS X 10.9 Mavericks 中一个显著的变化就是对 Foundation URL 加载系统的彻底重构. 现在已经有人在深入苹果的网络层基础架构的地方做研究了,所以我 ...
- iOS之网络请求NSURLSession剖析
2013年的WWDC大会上,苹果推出了NSURLSession,对Foundation URL加载系统进行了彻底的重构,提供了更丰富的API来处理网络请求,如:支持http2.0协议.直接把数据下载到 ...
- Cocoa Touch(五):网络请求 NSURLSession/AFNetworking, GCD, NSURLResquest
NSURLRequest 网络请求的关键的就是NSURLRequest类,它的实例表示了请求报文实体以及请求的缓存策略等等,各种网络框架的最终目标都是把这个对象编译成为请求报文发送出去.下面用一个实例 ...
- NSURLSession 网络请求
1.NSURLSession 在 iOS9.0 之后,以前使用的 NSURLConnection 过期,苹果推荐使用 NSURLSession 来替换 NSURLConnection 完成网路请求相关 ...
- swift开发网络篇—利用NSURLSession 发送GET和POST请求
说明:本文示例代码发送的请求均为http请求,需要对info.plist文件进行配置.如何配置,请参考https://github.com/HanGangAndHanMeimei/iOS9Adapta ...
随机推荐
- C#基础练习
1.冒泡排序 namespace _0 { class Program { public static int[] BubbleSort(int[] arr) { ; i < arr.Lengt ...
- php验证身份证号码的正确性
/********************php验证身份证号码是否正确函数*********************/function is_idcard( $id ) { $id = strto ...
- K-Means clusternig example with Python and Scikit-learn(推荐)
https://www.pythonprogramming.net/flat-clustering-machine-learning-python-scikit-learn/ Unsupervised ...
- TTTAttributedLabel xib sb lineSpacing not working
https://github.com/TTTAttributedLabel/TTTAttributedLabel/issues/733 set the same text in storyboard ...
- 连接池的实现 redis例子
# -*- encoding:utf-8 -*- # import pymysql # # conn = pymysql.connect(host="127.0.0.1", por ...
- 第一章 Shiro简介——《跟我学Shiro》(转)
目录贴:跟我学Shiro目录贴 1.1 简介 Apache Shiro是Java的一个安全框架.目前,使用Apache Shiro的人越来越多,因为它相当简单,对比Spring Security,可 ...
- 锁(MySQL篇)—之MyISAM表锁
前言 锁是计算机协调多个进程或线程并发访问某一资源的机制,在数据库中,除传统的计算资源(如CPU.RAM.I/O等)的争用以外,数据也是一种供许多用户共享的资源.如何保证数据并发访问的一致性.有效性是 ...
- 无法执行 FunctionImport“entitys.xx”,因为未将它映射到存储函数。EF
EF突然报了一个这样的错误: 无法执行 FunctionImport"entitys.xx",因为未将它映射到存储函数.EF 其中xx是存储过程: 可能是因为我在.edmx文件中& ...
- 导出excel报错
System.ComponentModel.Win32Exception: 拒绝访问 1.问题现象: foreach (System.Diagnostics.Process thispro in Sy ...
- 关于手机的内置SD卡与外置SD卡
对于安卓2.3的系统来说,Environment.getExternalStorageDirectory()获取的目录是内置SD卡还是外置SD卡是无法保证的, 和手机厂商的修改有关,只能通过Envir ...