代码实现网络接口请求数据
首先,这个只是我个人在一个已有工程中截取出来的代码块,相当于备忘录似的,对我自己来说还有点价值。
接口调用顺序:(以获得版本号为例)
1、首先通过[[WBNetworkEnginesharedInstance] getApplicationVertion:self];调用getApplicationVertion方法;
方法定义如下:
- (NSUInteger)getApplicationVertion:(id<WBNetworkEngineDelegate>)delegate { NSMutableDictionary * dict = [NSMutableDictionarydictionaryWithCapacity:0]; //dict包含需要传值的参素 WBAPIRequest *req = [WBAPIHelperrequestGetAPI:APPUPDATEparameter:dict target:self]; NSLog(@"req is %@",req); @synchronized(self){ [self.delegates setObject:delegate forKey:[NSNumber numberWithUnsignedInt:(unsigned int)(req)]]; } return (NSUInteger)req;//返回网络标识符 }
2、然后又通过 [WBAPIHelper requestGetAPI:APPUPDATE parameter:dict target:self];调用+ (WBAPIRequest *)requestGetAPI:(NSString *)action parameter:(NSDictionary *)parameter target:(id)delegate方法,
定义如下:
+ (WBAPIRequest *)requestGetAPI:(NSString *)action parameter:(NSDictionary *)parameter target:(id)delegate { NSMutableString * requestURL = [NSMutableString stringWithFormat:@"%@%@",BASEURL,action];//接口地址 //添加接口所必要的参数 for( id key in [parameter allKeys] ) { NSString * paramString = [WBAPIHelper stringOfParamter:key forValue:[parameter objectForKey:key]]; [requestURL appendFormat:@"&%@", paramString];//Adds a constructed string to the receiver. } //url中带中文时候的转换,否则无法创建request //传出过程中汉字被转换为十六进制,并且中间加上了"%"。解码时也应该用响应的编码方式进行解码 NSString *safestring=[requestURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; WBAPIRequest * req = [WBAPIHelper requestBaseAPI:[NSURL URLWithString:safestring]]; req.gcDelegate = delegate; [req setRequestMethod:@"GET"];//设置请求方法 [[WBAPIHelper httpQueue] addOperation:req];// Only add ASIHTTPRequests to this queue!! return req; }
3、方法中调用到以下三个在同一文件WBAPIHelper.m下定义的方法:
[WBAPIHelper stringOfParamter:key forValue:[parameter objectForKey:key]];
[WBAPIHelper requestBaseAPI:[NSURL URLWithString:safestring]];
[WBAPIHelperhttpQueue];
具体实现如下:
4、继而又通过[WBAPIRequest requestWithURL:url]调用+ (WBAPIRequest *) requestWithURL:(NSURL *)url方法:并且给返回网络字符加以[req addRequestHeader:@"Content-Type" value:@"application/json"];方法。
在requestWithURL中判断是否请求成功,成功则调用- (void)requestDone:(WBAPIRequest *)req方法,失败的话调用- (void)requestError:(WBAPIRequest *)req方法;
- (void)requestDone:(WBAPIRequest *)req { NSError *err = [req error]; int rspCode = [req responseStatusCode]; //返回状态码 NSLog(@"request url:%@, with method:%@", [req url], [req requestMethod]); NSLog(@"requst header: %@", [req requestHeaders]); if (!err && 200 == rspCode) { //200:方法调用成功 NSString *rspStr = [req responseString]; //Json解析 SBJsonParser * parser = [[SBJsonParser alloc] init]; NSDictionary *rsp = [parser objectWithString:rspStr]; [parser release]; if(self.gcDelegate != nil && [self.gcDelegate respondsToSelector:@selector(request:didSuccess:)]) { [self.gcDelegate performSelector:@selector(request:didSuccess:) withObject:self withObject:rsp]; }else{ //encounter error if (nil == err){ err = [NSError errorWithDomain:@"WBErrorDomainServer" code:rspCode userInfo:nil]; } if(self.gcDelegate != nil && [self.gcDelegate respondsToSelector:@selector(request:didSuccess:)]) { [self.gcDelegate performSelector:@selector(request:didFailed:) withObject:self withObject:err]; } } - (void)requestError:(WBAPIRequest *)req { DLOG(@"request url:%@, with method:%@", [req url], [req requestMethod]); DLOG(@"requst header: %@", [req requestHeaders]); NSError *err = [req error]; if(self.gcDelegate != nil && [self.gcDelegate respondsToSelector:@selector(request:didSuccess:)]) { [self.gcDelegate performSelector:@selector(request:didFailed:) withObject:self withObject:err]; }
4、到这里就要分成功和失败两种情况了,成功调用- (void)request:(SMAPIRequest *)request didSuccess:(NSDictionary *)rsp方法,失败调用- (void)request:(SMAPIRequest *)request didFailed:(NSError *)error:
5、最后成功返回信息到- (void)networkEngine:(WBNetworkEngine *)engine dataReceived:(NSDictionary *)data tag:(NSUInteger)tag方法中:
#pragma mark - WBNetworkEngineDelegate methods - (void)networkEngine:(WBNetworkEngine *)engine dataReceived:(NSDictionary *)data tag:(NSUInteger)tag { //获取版本信息 NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[[[data objectForKey:@"data"] objectAtIndex:0] objectAtIndex:0]]; NSString *serverVersion = [NSString stringWithFormat:@"%@",[dic objectForKey:@"version"]]; NSString *currentVersion = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"APPLICATIONVERSION"]]; //非首次进入,比较版本号 newVersion = [serverVersion intValue]; int oldVersion = [currentVersion intValue]; if (newVersion > oldVersion) { //有新版本更新,弹出更新弹出框 UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"有新内容,是否更新?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil]; [alter show]; [alter release]; } }
在该委托方法中data即是请求返回的值;可对其进行相关处理。
而失败的话则在- (void)networkEngine:(WBNetworkEngine *)engine error:(NSError *)err tag:(NSUInteger)tag方法中输出错误信息即可:
- (void)networkEngine:(WBNetworkEngine *)engine error:(NSError *)err tag:(NSUInteger)tag { DLOG(@"%@",err); }
其中在WBAPIRequest中定义的委托:
and在定义接口地址的类文件WBNetworkEngine中定义的委托: