访问网络的方式:
1、同步请求: 会阻塞主线程
2、异步请求: 无法取消 请求过程在多线程执行
基本流程:
1、构造NSURL实例。
2、生成NSURLRequest请求。
3、通过NSURLConnection发送请求。
4、通过NSURLRespond实例和NSError实例分析结果。
5、接受返回数据。
使用NSURLConnection发起异步请求:
第一种方法:
- (void)setUrl:(NSURL *)url
{
//使用同异步请求网络
NSMutableURLRequest *request = [[NSMutableURLRequest
alloc]init];
[request
setHTTPMethod:@"GET"];
//设置请求方式
[request
setURL:url];
//设置网络请求的url
[request setTimeoutInterval:60];//设置超出时间
//get请求不需要设置请求体
self.data = [NSMutableData
data];
[NSURLConnection
connectionWithRequest:request delegate:self];
}
//此种方法可以通过协议方法来监听数据加载的过程
几种常用的协议方法:
#pragma mark -
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData
*)data
{
[self.data
appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
UIImage *image = [UIImage
imageWithData:self.data];
self.image = image;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError
*)error
{
NSLog(@"请求失败!!!");
}
第二种方法:
- (void)setImageWithURL:(NSURL *)url
{
#if 0
//使用同步请求网络
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setHTTPMethod:@"GET"];
[request setURL:url];
[request setTimeoutInterval:60];
//get请求不需要设置请求体
NSURLResponse *response;
//发送同步请求
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
UIImage *image = [UIImage imageWithData:data];
self.image = image;
#endif
#if 1
//使用异步请求网络
NSMutableURLRequest *request = [[NSMutableURLRequest
alloc]init];
[request
setHTTPMethod:@"GET"];
[request
setURL:url];
[request setTimeoutInterval:60];
//get请求不需要设置请求体
// NSURLResponse *response;
//发送异步请求
NSOperationQueue *queue = [[NSOperationQueue
alloc]init];
[NSURLConnection
sendAsynchronousRequest:request
queue:queue completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
UIImage *image = [UIImage
imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
self.image = image; //主线程加载数据
});
}];
#endif
}
下面简单写一个NSURLConnection的封装代码
首先写封装 NSMutableURLRequest
的代码 得继承它
#import <Foundation/Foundation.h>
typedef
void(^FinshLoadBlock) (NSData *);
@interface PXRequest :
NSMutableURLRequest <NSURLConnectionDataDelegate>
@property (nonatomic,strong)NSMutableData *data;
//加载的数据
@property (nonatomic,strong)NSURLConnection *connection;
//连接对象
@property (nonatomic,strong)FinshLoadBlock block;
//定义一个block
数据加载完后调用
- (void)startAsynrc;
//开始请求
- (void)cancel;
//取消请求
@end
#import "PXRequest.h"
@implementation PXRequest
//开始异步请求
- (void)startAsynrc
{
self.data = [NSMutableData
data];
self.connection = [NSURLConnection
connectionWithRequest:self
delegate:self];
}
- (void)cancel
{
[self.connection
cancel];
}
#pragma mark -
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData
*)data
{
[self.data
appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.block(_data);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError
*)error
{
NSLog(@"出错信息 = %@",error);
}
@end
下面封装一段数据代码:
比如我要通过网络去访问一段天气接口
#import <Foundation/Foundation.h>
typedef void(^Completion)(id result);
//返回void
参数id 名字Completion
@interface PXDataService :
NSObject
//访问天气接口数据
+ (void)getWetheaData:(NSDictionary *)params block:(Completion)block;
@end
#import "PXDataService.h"
#import "PXRequest.h"
#define BASE_URL @"http://www.weather.com.cn/data/sk/"
@implementation PXDataService
//定义获取天气的接口
+ (void)getWetheaData:(NSDictionary *)params block:(Completion)block
{
NSString *cityCode = [params
objectForKey:@"code"];
NSString *urlstring = [BASE_URL
stringByAppendingFormat:@"%@.html",cityCode];
[self
startRequest:params
url:urlstring block:block
isGet:NO];
}
+ (void)startRequest:(NSDictionary *)param
url:(NSString *)urlString
block:(Completion)block
isGet:(BOOL)get
{
PXRequest *request = [PXRequest
requestWithURL:[NSURL
URLWithString:urlString]];
if(get)
[request
setHTTPMethod:@"GET"];
else
[request
setTimeoutInterval:60];
//如果是post请求则需要有请求体
一般格式是 username=zpx&password=1234
// [request setHTTPBody:<#(NSData *)#>]
[request
startAsynrc]; //开始请求网络
//当request的block执行时
会执行这里面的代码 block封装一段代码
request.block = ^(NSData *data){
NSString *datastring = [[NSString
alloc]initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(@"data = %@",datastring);
id ret = [NSJSONSerialization
JSONObjectWithData:data options:NSJSONReadingMutableContainers
error:nil];
//json解析
block(ret);
};
}
@end
主函数代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
*)launchOptions
{
self.window = [[UIWindow
alloc] initWithFrame:[[UIScreen
mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor
whiteColor];
[self.window
makeKeyAndVisible];
UIButton *button = [UIButton
buttonWithType:UIButtonTypeContactAdd];
button.frame =
CGRectMake(10,
50, 20,
20);
[button addTarget:self
action:@selector(load)
forControlEvents:UIControlEventTouchUpInside];
[self.window
addSubview:button];
return
YES;
}
- (void)load
{
NSDictionary *params =
@{@"code":@"101010300"};
[PXDataService
getWetheaData:params
block:^(id result) {
NSLog(@"result = %@",result); //打印加载完的数据
}];
}
点击按钮打印:
2014-07-08 23:08:20.862 WXDataServer[11527:60b] result = {
weatherinfo = {
Radar = "JC_RADAR_AZ9010_JB";
SD = "70%";
WD = "\U5317\U98ce";
WS = "0\U7ea7";
WSE = 0;
city = "\U671d\U9633";
cityid = 101010300;
isRadar = 1;
temp = 24;
time = "22:55";
};
}
使用NSURLConnection的网络请求与封装