异步连接

/创建一个字符串对象保存接口地址 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];
}

时间: 2024-07-28 19:50:45

异步连接的相关文章

NSURLConnection同步和异步连接

NSURLConnection去加载一个URL请求时候有两种方式,一种是同步加载,一种是异步加载. 同步加载会阻塞当前的那个线程,如果将同步加载的代码放在主线程里去执行,那么就会阻塞主线程. 异步加载一种方式使用的是block,就算将加载的代码放到主线程去执行,也不会阻塞主线程.异步加载的另一种方式比较灵活.它可以在你需要的时候去启动,在你不需要的时候可以取消. 先看一个在主线程种同步和异步,以及使用GCD同步三种方式加载数据的阻塞情况 // // AppDelegate.m // NSURLC

网络请求数据 get请求方式   post请求 协议异步连接服务器 block异步连接服务器

网络请求三部 创建一个请求(添加接口,对接口进行解码,) 设定请求方式(将接口转为NSURL,设置请求[请求地址, 缓存策略, 超时时间],设置请求方式) 连接服务器([同步连接,异步连接]代理连接,block连接) #import "MainViewController.h" @interface MainViewController () @property (retain, nonatomic) IBOutlet UIImageView *ImageWiew; //get请求方法

iOS网络编程--NSConnection的同步连接与异步连接

1 // 2 // ZFViewController.m 3 // 0628-表单验证 4 // 5 // Created by zfan on 14-6-28. 6 // Copyright (c) 2014年 zfan. All rights reserved. 7 // 8 9 #import "ZFViewController.h" 10 #import "MBProgressHUD+MJ.h" 11 12 @interface ZFViewControll

用tcpclient的异步连接方式,设置连接超时

如题 原理:异步连接,获取状态.阻止主进程等待异步进程返回.指定异步进程超时时间,这段时间内,如果异步连接没有返回,则以未完成状态返回,主进程继续. 根据对获取到的状态的识别,来判断是超时还是收到回应而使进程继续.再分别处理. 代码: static void Main(string[] args) { for (int i = 20; i <= 25; i++) { TcpClient tcp = new TcpClient(); IAsyncResult async = tcp.BeginCo

dw cs6 ajax 异步连接测试

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="

EF在异步连接MSSQL下报此连接不支持 MultipleActiveResultSets

ORM EF 数据库 MSSQL 2008 R2 场景 异步,没有发现在同步的场景下报错 异常 System.InvalidOperationException: 此连接不支持 MultipleActiveResultSets 解决方法 在连接字符串中添加 MultipleActiveResultSets = True 原文地址:https://www.cnblogs.com/mapleFlying/p/11465045.html

socket 异步接收连接和接收数据

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net.Sockets; using Syst

Java TCP异步数据接收

之前一直采用.Net编写服务端程序,最近需要切换到Linux平台下,于是尝试采用Java编写数据服务器.TCP异步连接在C#中很容易实现,网上也有很多可供参考的代码.但Java异步TCP的参考资料较少,网上例程多是阻塞多线程方法,由于线程的开销较大,当客户端较多时系统资源的消耗也较大. 综合网上和书本的相关知识,本文给出一个Java TCP异步接收数据的代码示例,并给出相关的注释. /** * TcpAsyncServer.java */ import java.nio.ByteBuffer;

struts2+ajax实现异步验证

由于老师布置作业的需要,在添加管理员的时候,要实现验证添加的管理员的用户名是否在数据库中已经存在,然后再客户端给用户一个提示.我首先想到的就是利用ajax实现异步验证技术,由于利用的ssh框架,所以在这要对struts2和ajax进行整合,由于我还没把ajax的一些知识总结出来,所以在这也不提了,有关ajax的详细内容将会在以后的博客中写出来.现在我们就以我做的这个添加管理员,验证管理员的用户名是否存在来说一下这个struts2+ajax实现异步验证技术. 首先我们来看一下我们的form表单: