iOS 开发中所需的数据基本都是来自网络,网络数据请求是 iOS 编程中必不可少的,应该熟练掌握网络请求.

网络请求方式有 :GET , POST , PUT ,DELETE 等,其中常用的就是 GET,POST . GET 和 POST 请求存在着不同,GET 将数据参数跟在 URL 后面,POST 参数放在 body 中,不可见.

数据请求方式分为同步请求和异步请求,其中常用的是异步请求,异步请求避免了因组线程阻塞而造成的崩溃.这里主要说下异步请求.

1.GET 同步请求 用 NSURLConnection 实现:

  步骤:建立 request ----> 建立衔接请求数据 ------> 解析数据

代码:

 #pragma mark --- get 同步 ---
- (IBAction)getOne:(id)sender {
self.allNewsArray = [[NSMutableArray alloc]init];
//url 地址
NSURL *url = [NSURL URLWithString:PATH];
//请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//建立衔接请求数据
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//如果数据不为空就解析
if (data) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options: error:nil];
//处理数据,用 model 存储
for (NSDictionary *dic1 in [dic objectForKey:@"news"]) {
NewsModel *model = [[NewsModel alloc]init];
[model setValuesForKeysWithDictionary:dic1];
[self.allNewsArray addObject:model];
} }
}

2.GET 异步请求 BLOCK 形式 用 NSURLConnection 实现

 #pragma mark --- get 异步请求 ---
- (IBAction)getTwo:(id)sender { self.allNewsArray = [[NSMutableArray alloc]init];
//url 地址
NSURL *url = [NSURL URLWithString:PATH];
//请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//默认是 get 方法,如果是 get 方法可以不写
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (data) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options: error:nil];
//处理数据,用 model 存储
for (NSDictionary *dic1 in [dic objectForKey:@"news"]) {
NewsModel *model = [[NewsModel alloc]init];
[model setValuesForKeysWithDictionary:dic1];
[self.allNewsArray addObject:model];
}
} }];
}

3.POST 异步请求 BLOCK 形式:用 NSURLConnection 实现

 #pragma mark --- POST 异步 Block 形式 ---
- (IBAction)POSTBlock:(id)sender { NSURL *URL = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; //制作包体
NSString *param = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; NSData *data = [param dataUsingEncoding:NSUTF8StringEncoding]; //设置请求方式
[request setHTTPMethod:@"POST"];
//设置 body
[request setHTTPBody:data];
[request setTimeoutInterval:]; //建立连接.请求数据
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { //解析数据
if (data) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options: error:nil];
//处理数据,用 model 存储
for (NSDictionary *dic1 in [dic objectForKey:@"news"]) {
NewsModel *model = [[NewsModel alloc]init];
[model setValuesForKeysWithDictionary:dic1];
[self.allNewsArray addObject:model];
}
} }];
}

4.POST 异步请求 delegate 形式:用 NSURLConnection 实现

 - (IBAction)POST_Delegate:(id)sender {

     NSURL *URL = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];

     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];

     //制作包体
NSString *param = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; NSData *data = [param dataUsingEncoding:NSUTF8StringEncoding]; //设置请求方式
[request setHTTPMethod:@"POST"];
//设置请求 body
[request setHTTPBody:data]; //建立连接请求数据
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self]; //启动请求
[conn start];
} - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"接收到响应"); self.data = [NSMutableData data]; } #pragma mark --- 接收数据的方法 ---
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.data appendData:data];
} #pragma mark --- 结束传递数据 ---
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.data options: error:nil];
NSLog(@"%@",dic); } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ }

5.GET 异步请求 SESSION 写法

 #pragma mark --- GET Session 写法 ---
- (IBAction)session:(id)sender { //创建 session 对象
NSURLSession *session = [NSURLSession sharedSession]; NSURL *URL = [NSURL URLWithString:PATH]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if(data){
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options: error:nil]; NSLog(@"%@",dic);
}
}]; //开始请求 (一定要调用)
[task resume];
}

6.POST 异步请求 BLOCK 形式:用 NSURLSession 实现

 - (IBAction)POST_Session:(id)sender {

     NSURL *URL = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];

     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];

     //制作包体
NSString *param = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; NSData *data = [param dataUsingEncoding:NSUTF8StringEncoding]; //设置请求方式
[request setHTTPMethod:@"POST"];
//设置请求 body
[request setHTTPBody:data]; NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",error); NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options: error:nil];
NSLog(@"%@",dic);
}]; [task resume];
}

iOS 网络编程的更多相关文章

  1. iOS网络编程模型

    iOS网络编程层次结构也分为三层: Cocoa层:NSURL,Bonjour,Game Kit,WebKit Core Foundation层:基于 C 的 CFNetwork 和 CFNetServ ...

  2. IOS网络编程——第三方类库

    IOS网络编程——第三方类库 目录 概述 ASIHttpRequest AFNetworking 其他 概述 ASIHttpRequest AFNetworking 其他

  3. IOS网络编程:HTTP

    IOS网络编程:HTTP HTTP定义了一种在服务器和客户端之间传递数据的途径. URL定义了一种唯一标示资源在网络中位置的途径. REQUESTS 和 RESPONSES: 客户端先建立一个TCP连 ...

  4. iOS网络编程笔记——Socket编程

    一.什么是Socket通信: Socket是网络上的两个程序,通过一个双向的通信连接,实现数据的交换.这个双向连路的一端称为socket.socket通常用来实现客户方和服务方的连接.socket是T ...

  5. 浅谈iOS网络编程之一入门

    计算机网络,基本上可以抽象是端的通信.实际在通讯中会用到不同的设备,不同的硬件中,为了能友好的传输信息,那么建立一套规范就十分必要了.先来了解一些基本概念 了解网络中传输的都是二进制数据流.  2.了 ...

  6. iOS 网络编程:socket

    @import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/c ...

  7. iOS 网络编程模式总结

    IOS 可以采用三类api 接口进行网络编程,根据抽象层次从低到高分别为socket方式.stream方式.url 方式. 一 .socket 方式 IOS 提供的socket 方式的网络编程接口为C ...

  8. ios网络编程(入门级别)-- 基础知识

    在学习ios的过程中,停留在UI控件很长时间,现在正在逐步的接触当中!!!!!!在这个过程中,小编学到了一些关于网络编程知识,并且有感而发,在此分享一下: 关于网络请求的重要性我想不用多说了吧!!!对 ...

  9. iOS 网络编程(HTTP协议)

    HTTP协议的概念HTTP协议,Hyper Text Transfer Protocol (超文本传输协议)是用于从万维网服务器传送超文本到本地浏览器的传输协议,HTTP是一个应用层协议,由请求和响应 ...

  10. 从socket开始讲IOS网络编程

    home list tags talk user rss Mac&iOS Socket 大纲 一.Socket简介 二.BSD Socket编程准备 1.地址 2.端口 3.网络字节序 4.半 ...

随机推荐

  1. (转).net项目技术选型总结

    原文作者:mcgrady 原文地址:.net项目技术选型总结 做.net开发已经几年了,也参与开发了很多大大小小的项目,所以现在希望总结出一套开发.net项目的常用技术,也为以后做项目技术选型的时候作 ...

  2. Jersey(1.19.1) - Security

    Security information is available by obtaining the SecurityContext using @Context, which is essentia ...

  3. IIS实现301重定向

    301永久重定向对SEO无任何不好的影响,而且网页A的关键词排名和PR级别都会传达给网页B,网站更换了域名,表示本网页永久性转移到另一个地址,对于搜索引擎优化|SEO来说,给搜索引擎一个友好的信息,告 ...

  4. OC10_文件练习

    // // TextHander.h // OC10_文件练习 // // Created by zhangxueming on 15/6/19. // Copyright (c) 2015年 zha ...

  5. 《HTML5网页开发实例详解》连载(四)HTML5中的FileSystem接口

    HTML 5除了提供用于获取文件信息的File对象外,还添加了FileSystem相关的应用接口.FileSystem对于不同的处理功能做了细致的分类,如用于文件读取和处理的FileReader和Fi ...

  6. CAF(C++ actor framework)(序列化之结构体,任意嵌套STL)(一)

    User-Defined Data Types in Messages(用户自定义类型)All user-defined types must be explicitly “announced” so ...

  7. SQL server 常见用法记录

        -- ============================================= -- Author:                tanghong -- Create da ...

  8. 类似QQ的应用毗邻(Pilin)即时聊天源码

      这个应用是从安卓教程网分享过了的,个人觉得这个还是挺不错的,毗邻(Pilin)即时聊天应用源码,承诺的 基于xmpp openfire asmack 的即时聊天应用,继续完善,现在只完成了文字.表 ...

  9. ArcGIS Server10.1授权文件

    3dengine,101,ecp.arcgis.server,01-jan-2020,UTE784S3EY83ZJKN0085 3dserver,101,ecp.arcgis.server,01-ja ...

  10. Spark Streaming揭秘 Day34 解析UI监听模式

    Spark Streaming揭秘 Day34 解析UI监听模式 今天分享下SparkStreaming中的UI部分,和所有的UI系统一样,SparkStreaming中的UI系统使用的是监听器模式. ...