iOS中GET 和 POST 数据请求

本文涉及的产品
云解析 DNS,旗舰版 1个月
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
全局流量管理 GTM,标准版 1个月
简介:  iOS中GET 和 POST 网络数据请求 同步请求和异步请求的差别:  1.同步请求,有主线程完成网路请求任务,在数据没有请求之前,用户的所有的交互事件应用都无法处理,会造成一种卡顿现象,影响用户体验  2.

 iOS中GET 和 POST 网络数据请求

同步请求和异步请求的差别:

 1.同步请求,有主线程完成网路请求任务,在数据没有请求之前,用户的所有的交互事件应用都无法处理,会造成一种卡顿现象,影响用户体验

 2.异步同步,系统默认开辟子线程完成网络请求任务,主线程依然会处理用户的交互事件,此时不会出现卡顿,一旦开辟子线程就会消耗资源(内存),此时就是拿空间换时间

先分析下整体思路:


1.下面准备一个公用的model数据数据模型:

Business.h

#import <Foundation/Foundation.h>
@interface Business : NSObject
@property(nonatomic,copy)NSString *name;//商户名
@property(nonatomic,copy)NSString *address;//商户地址
@property(nonatomic,copy)NSString *telephone;//电话号码
@property(nonatomic,copy)NSString *title;
@property(nonatomic,copy)NSString *summary;
@end
Business.m

#import "Business.h"
@implementation Business
- (void)dealloc{
    self.name = nil;
    self.telephone = nil;
    self.address = nil;
    self.title = nil;
    self.summary = nil;
    [super dealloc];
}
//防止Crash
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
 
}
@end

2.下面准备两个自定义的cell用于两种数据请求的自定义cell
第一个自定义cell:

BusinessCell.h

#import <UIKit/UIKit.h>
@class Business;
@interface BusinessCell : UITableViewCell
@property (retain, nonatomic) IBOutlet UILabel *nameLabel;
@property (retain, nonatomic) IBOutlet UILabel *adressLabel;
@property (retain, nonatomic) IBOutlet UILabel *telephoneLabel;
//写一个接口给cell上的子控件赋值
- (void)assignValueByBusiness : (Business *)business;
@end

BusinessCell.m

#import "BusinessCell.h"
#import "Business.h"
@implementation BusinessCell

- (void)awakeFromNib {
    // Initialization code
}

//写一个接口给cell上的子控件赋值
- (void)assignValueByBusiness : (Business *)business{
    
    self.nameLabel.text = business.name;
    self.telephoneLabel.text = business.telephone;
    self.adressLabel.text = business.address;
   
    
}
- (void)dealloc {
    [_nameLabel release];
    [_adressLabel release];
    [_telephoneLabel release];
    [super dealloc];
}@end
第二个自定义cell:

CustomCell.h

#import <UIKit/UIKit.h>
@class Business;
@interface CustomCell : UITableViewCell
@property (retain, nonatomic) IBOutlet UILabel *titleLabel;
@property (retain, nonatomic) IBOutlet UILabel *summaryLabel;
//写一个方法给cell上的控件赋值
- (void)setValueByName : (Business *)business;
@end
CustomCell.m

#import "CustomCell.h"
#import "Business.h"
@implementation CustomCell
- (void)dealloc {
    
    [_titleLabel release];
    [_summaryLabel release];
    [super dealloc];
}
//写一个方法给cell上的控件赋值
- (void)setValueByName : (Business *)business{
    
    self.titleLabel.text = business.title;
    self.summaryLabel.text = business.summary;
}@end

——————————————开始介绍数据请求:————————————————

GET数据请求(同步请求):
<span style="color:#3333ff;">#import "GETViewController.h"
#import "Business.h"
#import "CustomCell.h"
#import "BusinessCell.h"
@interface GETViewController ()<NSURLConnectionDataDelegate>
@property(nonatomic,retain)NSMutableArray *dataSource;
@property(nonatomic,retain)NSMutableData *data;//拼接多次请求下来的数据
@end

@implementation GETViewController
- (void)dealloc{
    self.dataSource = nil;
    self.data = nil;
    [super dealloc];
}

//懒加载
- (NSMutableArray *)dataSource{
    if (_dataSource == nil) {
        self.dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return [[_dataSource retain]autorelease];
}

</span><span style="color:#ff0000;">//同步get请求</span><span style="color:#3333ff;">
- (IBAction)handleGetSyncRequst:(UIBarButtonItem *)sender {
    
    //清空数组
    [self.dataSource  removeAllObjects];
    
    //1.准备网址字符串
    NSString *urlStr = @"http://api.map.baidu.com/place/v2/search?query=大保健&region=上海&output=json&ak=6E823f587c95f0148c19993539b99295";
    //2.查看网址字符串中是否含有中文,有中文的话要对urlStr进行转码
    NSString *changeUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //3.创建NSURL对象,不能能够存储本地的文件地址,也能存储网络地址
    NSURL *url = [NSURL URLWithString:changeUrlStr];
    
    //4.创建网络请求对象(NSURLRequest )
    // NSURLRequest 默认请求方式就是GET请求
    // NSMutableURLRequest  可以设置网络的请求方式
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
   
    //5.建立同步链接
    //5.1 创建服务器响应对象
    NSURLResponse *response = nil;
    //5.2 创建请求失败错误信息对象
    //以上两个参数都是方法的内部对其赋值
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//    NSLog(@"%@",data); 验证!
    
    //调用解析方法
    [self parserData:data];
    
    }
//封装一个解析的方法
- (void)parserData : (NSData *)data{
    
    //解析:
    NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    //    NSLog(@"%@",dataDic); 验证!
    //取出results key值对应的数组
    NSArray *array = dataDic[@"results"];
    //遍历数组的字典,并使用给Business对象赋值
    for (NSDictionary *dic in array) {
        //创建数据模型对象
        Business *bus = [[Business alloc]init];
        
        //使用kvc给bus赋值
        [bus setValuesForKeysWithDictionary:dic];
        
        //添加到存储所有商户信息的数组
        [self.dataSource addObject:bus];
        //释放
        [bus release];
        //        NSLog(@"%@",self.dataSource); 验证!
        
        
    }
    //刷新ui界面
    [self.tableView reloadData];
}</span>
GET数据请求(异步请求):
<span style="color:#ff0000;">//异步get请求</span>
- (IBAction)handleGetAsyncRequst:(UIBarButtonItem *)sender {
    
    //清空数组
    self.dataSource = nil;
    
    //1.创建网址字符串
    NSString *urlStr = @"http://api.map.baidu.com/place/v2/search?query=大保健&region=上海&output=json&ak=6E823f587c95f0148c19993539b99295";
    //2.判断是否含有中文
    NSString *change = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //3.创建NSURL对象
    NSURL *url = [NSURL URLWithString:change];
    //4.创建网络请求
    NSURLRequest *requst = [NSURLRequest requestWithURL:url];
    //5.创建异步网络连接
//    NSOperationQueue  队列类
//    [NSOperationQueue mainQueue]   获取主队类
    
    
    /*
    //让当前的self 对象处于引用状态
    __block typeof(self) weakSelf = self;
    [NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        //data 就是请求下来的数据
        //response 就是响应对象
        //connectionError 就是存放连接时报错信息的对象
        //调用解析方法
        [weakSelf parserData:data];
    }];
    */
    
   <span style="color:#ff0000;"> //代理完成异步解析</span>
    [NSURLConnection connectionWithRequest:requst delegate:self];
  
}

代理完成异步解析:

#pragma mark NSURLConnection 代理方法
//当接收到服务器响应的时候触发
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    //一旦接收到服务器的响应,就创建拼接的data对象
    self.data = [NSMutableData data];
}
//当接收到服务器数据的时候触发
//此方法有可能触发多次,原因:1.网络环境比较差时 2.请求的数据量比较大的时候,此时服务器会分多次把数据传输过来
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    //拼接服务器传输的数据
    [self.data appendData:data];
}
//当接收到服务器传输数据结束的时候触发
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    //此时数据已经接收完毕,可以解析了
    [self parserData:self.data];
}
显示在控件上:

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        BusinessCell *cell = [tableView dequeueReusableCellWithIdentifier:@"getcell" forIndexPath:indexPath];
    //调用cell的控件的赋值方法
    [cell assignValueByBusiness:self.dataSource[indexPath.row]];
    return cell;
}
GET两种数据请求完成!

查看效果:

GET同步和异步数据请求效果:

     ——————————    


————————————————POST数据请求——————————————————————
定义相关属性:

#import "POSTViewController.h"
#import "Business.h"
#import "CustomCell.h"

@interface POSTViewController ()
@property(nonatomic,retain)NSMutableArray *dataSource;
@end

@implementation POSTViewController
- (void)dealloc{
    self.dataSource = nil;
    [super dealloc];
}
- (NSMutableArray *)dataSource{
    if (_dataSource == nil) {
        self.dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return [[_dataSource retain]autorelease];
}


POST同步数据请求:
//Post同步
//http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx/
//date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213
- (IBAction)handlePostSyncRequst:(UIBarButtonItem *)sender {


    [self.dataSource removeAllObjects];
    
    //1.准备网址字符串
    NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx/";
    //2.创建NSURL对象
    NSURL *url = [NSURL URLWithString:urlStr];
    //3.创建网络请求对象
    NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:url];
    //3.1配置请求方式
    requst.HTTPMethod = @"POST";
    //4.创建参数字符串
    NSString *bodyString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
    //将字符串转换为NSDate独享
    NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    //配置网络请求的方式
    requst.HTTPBody = data;
    
    //5.创建网络链接
    NSURLResponse *response = nil;
    NSError *error = nil;
  NSData *data1 =  [NSURLConnection sendSynchronousRequest:requst returningResponse:&response error:&error];
    
//    NSLog(@"%@",data1);
    
    [self parserData: data1];

    
}


POST同步数据请求:
//post异步
- (IBAction)handlePostAsyncRequest:(UIBarButtonItem *)sender {

    [self.dataSource removeAllObjects];
    
    //1.创建网址字符串
    NSString *urlStr =  @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx/";
    //2.创建NSURL对象
    NSURL *url = [NSURL URLWithString:urlStr];
    //3.创建网络请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //3.1创建请求方式
 request.HTTPMethod = @"POST";
    //4.创建参数对象
    NSString *bodyString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
    NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    //设置请求对象的body
    request.HTTPBody = data;
    
    //5.创建网络链接
    __block typeof(self) weakself = self;
    
  [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//      NSLog(@"%@",data);
      
      [weakself parserData:data];
     
  }];
   
}


封装一个解析的方法

- (void)parserData : (NSData *)data{
    
    //解析:
    NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"%@",dataDic); //验证!
    //取出results key值对应的数组
    NSArray *array = dataDic[@"news"];
//    NSLog(@"%@",array);
    //遍历数组的字典,并使用给Business对象赋值
    for (NSDictionary *dic in array) {
        //创建数据模型对象
        Business *bus = [[Business alloc]init];
        
        //使用kvc给bus赋值
        [bus setValuesForKeysWithDictionary:dic];
//        NSLog(@"%@",bus);
        //添加到存储所有商户信息的数组
        [self.dataSource addObject:bus];
        //释放
        [bus release];
//                NSLog(@"%@",self.dataSource); //验证!
        
        
    }
    //刷新ui界面
    [self.tableView reloadData];
}
显示在控件上:
- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Return the number of rows in the section.
    return self.dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"post" forIndexPath:indexPath];
    
    [cell setValueByName:self.dataSource[indexPath.row]];
    
    return cell;
}

POST两种数据请求完成!

查看两种效果效果:
————————————



————————————————————————————————————————————

——————————————介绍同步卡顿现象——————————————————————

BigImageViewController.m

@interface BigImageViewController ()
@property (retain, nonatomic) IBOutlet UIImageView *bigImageView;
@end

@implementation BigImageViewController
- (IBAction)handleKaDun:(UIButton *)sender {
    
    //1.准备网址字符串
    NSString *urlStr = @"http://f1.topit.me/1/d2/8c/11663656284128cd21o.jpg";
    
    //2.初始化NSURL对象
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //3.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //4.建立网络连接
    //4.1创建响应度向
    NSURLResponse  *response = nil;
    NSError *errror = nil;
 NSData *data =   [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&errror];
    
    //音乐数据,视频数据,图片数据不需要解析直接可以使用
    self.bigImageView.image = [UIImage imageWithData:data];
    
}
效果展示:

————————————————————————————————————————————



目录
相关文章
|
4月前
|
开发框架 前端开发 Android开发
Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势
本文深入探讨了 Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势。这对于实现高效的跨平台移动应用开发具有重要指导意义。
439 4
|
7月前
|
iOS开发 开发者
iOS平台RTMP|RTSP播放器如何实时回调YUV数据
我们在做RTMP、RTSP播放器的时候,有开发者需要自己处理拉取到的YUV数据,做二次分析之用,为此,我们做了以下的设计:InitPlayer之后,再调用SmartPlayerStart()接口之前,设置yuv数据回调即可。
|
10月前
|
Java iOS开发
iOS的数据序列化(又称持久化)的两类使用方式
iOS的数据序列化(又称持久化)的两类使用方式
90 0
|
10月前
|
Java 开发工具 Android开发
SLS:使用 OTel 官方 SDK 采集 Android、iOS Trace 数据实践
本文介绍了使用 OTel 官方 SDK 采集 Android、iOS Trace 数据实践。
610 7
SLS:使用 OTel 官方 SDK 采集 Android、iOS Trace 数据实践
|
10月前
|
移动开发 小程序 API
uniapp通过蓝牙传输数据 (ios)
uniapp通过蓝牙传输数据 (ios)
450 1
|
10月前
|
JSON JavaScript 安全
iOS应用程序数据保护:如何保护iOS应用程序中的图片、资源和敏感数据
iOS应用程序数据保护:如何保护iOS应用程序中的图片、资源和敏感数据
91 1
|
10月前
|
Web App开发 网络安全 Android开发
🚀2023最新版克魔助手抓包教程(9) - 克魔助手 IOS 数据抓包
在移动应用程序的开发中,了解应用程序的网络通信是至关重要的。数据抓包是一种很好的方法,可以让我们分析应用程序的网络请求和响应,了解应用程序的网络操作情况。克魔助手是一款非常强大的抓包工具,可以帮助我们在 Android 和 iOS 平台上进行数据抓包。本篇博客将介绍如何使用克魔助手在 iOS 平台上进行数据抓包。
|
存储 SQL 数据库
iOS 数据持久化方案-Realm的使用(下)
iOS 数据持久化方案-Realm的使用(下)
599 0
iOS 数据持久化方案-Realm的使用(下)
|
SQL 存储 数据可视化
iOS 数据持久化方案-Realm的使用(上)
iOS 数据持久化方案-Realm的使用(上)
1059 0
iOS 数据持久化方案-Realm的使用(上)
|
存储 开发框架 C#
iOS数据持久化之二——归档与设计可存储化的数据模型基类(二)
iOS数据持久化之二——归档与设计可存储化的数据模型基类
236 0
iOS数据持久化之二——归档与设计可存储化的数据模型基类(二)

热门文章

最新文章

  • 1
    【01】噩梦终结flutter配安卓android鸿蒙harmonyOS 以及next调试环境配鸿蒙和ios真机调试环境-flutter项目安卓环境配置-gradle-agp-ndkVersion模拟器运行真机测试环境-本地环境搭建-如何快速搭建android本地运行环境-优雅草卓伊凡-很多人在这步就被难倒了
  • 2
    iOS|解决 setBrightness 调节屏幕亮度不生效的问题
  • 3
    【03】仿站技术之python技术,看完学会再也不用去购买收费工具了-修改整体页面做好安卓下载发给客户-并且开始提交网站公安备案-作为APP下载落地页文娱产品一定要备案-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
  • 4
    【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
  • 5
    Cellebrite UFED 4PC 7.71 (Windows) - Android 和 iOS 移动设备取证软件
  • 6
    【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
  • 7
    iOS各个证书生成细节
  • 8
    iOS|记一名 iOS 开发新手的前两次 App 审核经历
  • 9
    iOS MapView(定位)
  • 10
    iOS 自定义字体
  • 1
    iOS|解决 setBrightness 调节屏幕亮度不生效的问题
    113
  • 2
    iOS|记一名 iOS 开发新手的前两次 App 审核经历
    20
  • 3
    iOS各个证书生成细节
    29
  • 4
    【01】噩梦终结flutter配安卓android鸿蒙harmonyOS 以及next调试环境配鸿蒙和ios真机调试环境-flutter项目安卓环境配置-gradle-agp-ndkVersion模拟器运行真机测试环境-本地环境搭建-如何快速搭建android本地运行环境-优雅草卓伊凡-很多人在这步就被难倒了
    151
  • 5
    Cellebrite UFED 4PC 7.71 (Windows) - Android 和 iOS 移动设备取证软件
    50
  • 6
    【03】仿站技术之python技术,看完学会再也不用去购买收费工具了-修改整体页面做好安卓下载发给客户-并且开始提交网站公安备案-作为APP下载落地页文娱产品一定要备案-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
    66
  • 7
    【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
    54
  • 8
    【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
    51
  • 9
    uniapp开发ios打包Error code = -5000 Error message: Error: certificate file(p12) import failed!报错问题如何解决
    163
  • 10
    【05】2025年1月首发完整版-篇幅较长-苹果app如何上架到app store完整流程·不借助第三方上架工具的情况下无需花钱但需仔细学习-优雅草央千澈详解关于APP签名以及分发-们最关心的一篇来了-IOS上架app
    352