异步连接
异步连接
/创建一个字符串对象保存接口地址 NSString *str =
@"http://project.lanou3g.com/teacher/yihuiyun/lanou project/activitylist.php";
//创建一个NSURL对象,保存,请求的信息
NSURL *url = [NSURL URLWithString:str];
//创建一个请求对象,携带NSURL对象,进行请求
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
//异步连接,实现请求过程,可以从服务器端获取到 response.data.error
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//将获取到的data对象,转换成我们想要的容器对象,取决 于我们的数据格式,到底是字典ahishi数组
NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
//获取到我们借口中,存储具体信息的数据数组
NSArray *dataArray = [dataDic objectForKey:@"events"];
NSLog(@"数据数组%@",dataArray);
//forin遍历,将接口数据数组中的每个字典得到,KVC转 换成模型,再将模型放在我们表示图需要的数据源数组中去,进行使用
NSMutableArray *inforArray = [NSMutableArray arrayWithCapacity:[dataArray count]];
for (NSDictionary *dic in dataArray) { Event *event = [[Event alloc] init];
[event setValuesForKeysWithDictionary:dic];
[inforArray addObject:event];
NSLog(@"address%@",event.address); }
//重新加载数据
[self.tableView reloadData];
}]; }
#import "RootViewController.h"
#import "Event.h"
@interface RootViewController ()
@property (nonatomic, retain) NSMutableData *mData; @property (nonatomic)long long totalLength; @property (nonatomic, retain) AVAudioPlayer *player; @property (nonatomic, retain) Event *event;
@end
@implementation RootViewController
//代理请求数据 //可以接收到请求返回的response
-(void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response
{
_totalLength = response.expectedContentLength; //回应的时候就开始初始化,初始化我们的_mData;
_mData = [NSMutableData data];
NSLog(@"%@",response); }
//可以接收请求返回的data对象 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//将data拼接打牌_mData里
[_mData appendData:data];
NSLog(@"---------%.2f%%",100.0 * [_mData length]
/ _totalLength);
}
//请求完成之后执行的方法
-(void)connectionDidFinishLoading:(NSURLConnection
*)connection
{
NSLog(@"请求完成");
_player = [[AVAudioPlayer alloc]
initWithData:_mData error:nil]; [_player play];
}
//如果请求失败,可以接受到错误信息
-(void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
NSLog(@"%@",error); }
- (void)asynGET
{
#pragma mark ----------------异步连接
GET-------------------
//字符串对象,get请求的最大特点就是参数直接跟在URL后面, 中间以?分隔
NSString *str = @"http://lx.cdn.baidupcs.com/file/5d6bd385c2bbcebbd af8dbd2a1fbb475?bkt=p2-qd-379&xcode=77f7e61f11aa5fe b9cc29fbcaf636d95b618b2c52e59dfa4ed03e924080ece4b&f id=2756918354-250528-139183155092638&time=143885195 7&sign=FDTAXERLBH-DCb740ccc5511e5e8fedcff06b081203- vaupF7kySxfl2WEPsiB9PA1IIxA%3D&to=hc&fm=Nan,B,T,t&s ta_dx=4&sta_cs=814&sta_ft=mp3&sta_ct=5&fm2=Nanjing, B,T,t&newver=1&newfm=1&secfm=1&flow_ver=3&sl=773980 95&expires=8h&rt=sh&r=599721095&mlogid=1550793129&v
uk=-&vbdid=1570913133&fin=%E6%83%85%E8%AF%9D.mp3&fn =%E6%83%85%E8%AF%9D.mp3&slt=pm&uta=0&rtype=1&iv=0&i sw=0";
//讲一个字符串对象转化成一个NSURL对象
NSURL *url = [NSURL URLWithString:str];
//创建一个请求对象
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
//异步连接,连接客户端和服务器
NSURLConnection *conection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conection start]; }
- (void)asynPOST {
//创建一个字符串
NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/pu blish/Handler/APINewsList.ashx";
//创建一个NSURL对象
NSURL *url = [NSURL URLWithString:str];
//创建POST请求对象,因为NSURLRequest这个类默认的请求方
式是GET,所以没法实现POST请求,我们采用 NSMutableURLRequest这个类来创建对象,post与get的最大区别 在于,post请求将url中的参数部分分离出来
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
//设置请求方式
[request setHTTPMethod:@"POST"];
//字符串转化为NSData对象 //分离出来的参数部分放到了body体里面
[request setHTTPBody:[@"date=20131129&startRecord=1&len=5&ud id=1234567890&terminalType=Iphone&cid=213" dataUsingEncoding:NSUTF8StringEncoding]];
//异步连接
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// // //
if (connectionError) { NSLog(@"网络错误");
}else{
NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@",dataDic); // }
//
}]; }
[self.tableView reloadData];
//每日精选我们使用了Block,这个页面我们使用代理请求 NSURL *url = [NSURL
URLWithString:@"http://baobab.wandoujia.com/api/v1/ categories"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//代理请求
[NSURLConnection connectionWithRequest:request delegate:self];
}
//- (NSURLRequest *)connection:(NSURLConnection
*)connection willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)response
//{
//
//}
//可以接收到请求返回的response
- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response
{
//初始化data,方便下面的方法 做拼接(如果不在这里初始化, 可以做个懒加载);
self.pastData = [NSMutableData data]; }
- (void)connection:(NSURLConnection *)connection
didReceiveData:(NSData *)data
{
//拼接数据
[self.pastData appendData:data]; }
-(void)connectionDidFinishLoading:(NSURLConnection
*)connection
{
//数据请求完毕后,对拼接完成的数据做解析
//因为数据的 根目录是一个数组,所以我们拿一个数组来接收它 NSArray *array = [NSJSONSerialization
JSONObjectWithData:self.pastData options:0 error:nil];
//一般在forin前面初始化我们的数组.因为我们这里也不会去 做上拉加载更多,所以我们用不到懒加载
self.array = [NSMutableArray array]; for (NSDictionary *dic in array) {
PastModel *model = [[PastModel alloc] initWithDictionary:dic];
[self.array addObject:model]; }
//刷新数据,一定要记得写,养成一个习惯,就像写; 一样.
[self.collectionView reloadData]; }