这个类通过block的方法,把这个类请求的数据,返回到视图控制器
typedefvoid(^Block)(idresult);
GET方法
+ (void)NetWorkingToolURL:(NSString*)strURL result:(Block)block;
+ (void)NetWorkingToolURL:(NSString*)strURL result:(Block)block{
NSString*strEncode = [strURLstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL*url = [NSURLURLWithString:strEncode];
NSMutableURLRequest*request = [NSMutableURLRequestrequestWithURL:url];
[NSURLConnectionsendAsynchronousRequest:requestqueue:[NSOperationQueuemainQueue]completionHandler:^(NSURLResponse*response,NSData*data,NSError*connectionError) {
idresult = [NSJSONSerializationJSONObjectWithData:dataoptions:0error:nil];
//把json处理好的数据,通过block进行回调,返回到视图控制器
block(result);
}];
}
[NetWorkingToolNetWorkingToolURL:@"http://api.map.baidu.com/place/v2/search?query=银行®ion=大连&output=json&ak=6E823f587c95f0148c19993539b99295"result:^(idresult) {
NSMutableDictionary*dic = result;
NSLog(@"%@",dic);
}];
********************************************************************************
用协议的方法
@protocolNetWorkingDelegate
- (void)getData:(id)result;
@end
@interfaceNetWorkingDelegate :NSObject
#pragma mark -设置代理人属性
@property(nonatomic,assign)iddelegate;
- (void)netWorkingWithURL:(NSString*)strURL;
+ (void)netWorkingWithURL:(NSString*)strURL delegate:(id)delegate;
减号方法
- (void)netWorkingWithURL:(NSString*)strURL{
//因为没有办法保证网址没有中文,所以需要先对传过来的字符串进行转换
NSString*strEncode = [strURLstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//创建一个url
NSURL*url = [NSURLURLWithString:strEncode];
//创建请求
NSMutableURLRequest*request = [NSMutableURLRequestrequestWithURL:url];
//用block事先异步
[NSURLConnectionsendAsynchronousRequest:requestqueue:[NSOperationQueuemainQueue]completionHandler:^(NSURLResponse*response,NSData*data,NSError*connectionError) {
//对数据进行json解析
idresult = [NSJSONSerializationJSONObjectWithData:dataoptions:0error:nil];
//对已经处理好的数据通过协议方法带到VC里
[self.delegategetData:result];
}];
}
加号方法
+ (void)netWorkingWithURL:(NSString*)strURL delegate:(id)delegate{
//把网络请求这几步重新写一遍
NSString*strEncode = [strURLstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL*url = [NSURLURLWithString:strEncode];
NSMutableURLRequest*request = [NSMutableURLRequestrequestWithURL:url];
[NSURLConnectionsendAsynchronousRequest:requestqueue:[NSOperationQueuemainQueue]completionHandler:^(NSURLResponse*response,NSData*data,NSError*connectionError) {
idresult = [NSJSONSerializationJSONObjectWithData:dataoptions:0error:nil];
[delegategetData:result];
}];
}
//创建一个网络工程类的对象
NetWorkingDelegate*tool = [[NetWorkingDelegatealloc]init];
//设置代理人
tool.delegate=self;
//让对象去调用方法
[toolnetWorkingWithURL:@"http://api.map.baidu.com/place/v2/search?query=银行®ion=大连&output=json&ak=6E823f587c95f0148c19993539b99295"];