ios中封裝網路請求類
ios中封裝網路請求類#import "JSNetWork.h"//asiHttpRequest#import "ASIFormDataRequest.h"//xml 的解析#import "UseXmlParser.h"//判斷是否連網#import "Reachability.h"//sbJson,判斷json的解析#import "JSON.h"@implementation JSNetWork//建立一個單例+(JSNetWork*)shareNetWork{ static JSNetWork *network = NULL; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ network = [[self alloc] init]; }); return network;}-(NSString*)JiangSuApiCacheFileName:(NSString*)fileName{ NSString * cacheFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; cacheFolder = [cacheFolder stringByAppendingPathComponent:@"JiangSu"]; NSFileManager * fmgr = [NSFileManager defaultManager]; if (![fmgr fileExistsAtPath:cacheFolder]) { NSError * error; [fmgr createDirectoryAtPath:cacheFolder withIntermediateDirectories:YES attributes:nil error:&error]; } cacheFolder = [cacheFolder stringByAppendingPathComponent:fileName]; return cacheFolder;}-(NSDictionary*)getURLFromPlistWithKey:(NSString*)plKey{ NSString *path = [[NSBundle mainBundle] pathForResource:@"JiangSuURL" ofType:@"plist"]; NSDictionary *urlDic = [NSDictionary dictionaryWithContentsOfFile:path]; return ASDynamicCast(NSDictionary, [urlDic valueForKey:plKey]);}//網路請求方式--因為是單例所有傳遞的值要不同 必須加connectId-(void)JSNetWorkWith:(int)connectID Body:(NSString*)bodyString PostBody:(NSString*)postBody Delegate:(id)aDelegate{ //判斷是否連網 if (![self isConnectNetWork]) { UIAlertView *myalert = [[UIAlertView alloc] initWithTitle:nil message:@"請串連網路後再使用" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil]; myalert.tag = 0x9999; [myalert show]; [myalert release]; if (aDelegate && [aDelegate respondsToSelector:@selector(NetWorkBackConnectID:BackString:WithNetState:)]) { [aDelegate NetWorkBackConnectID:connectID BackString:nil WithNetState:0]; } return; } if ([bodyString hasPrefix:@"http"] == NO) { bodyString = [NSString stringWithFormat:@"%@/%@",HTTPURLPREFIX,bodyString]; } ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:bodyString]]; [request setDelegate:self]; request.timeOutSeconds = 20; [request setRequestMethod:@"POST"]; [request addRequestHeader:@"Content-Type" value:@"application/xml;charset=UTF-8;"]; NSArray *aa = [postBody componentsSeparatedByString:@"&"]; for (NSString *str in aa) { NSArray *bb = [str componentsSeparatedByString:@"="]; [request setPostValue:[bb objectAtIndex:1] forKey:[bb objectAtIndex:0]]; } //傳遞參數 [request setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",connectID],@"tag",aDelegate,@"target", nil]]; [request startAsynchronous];}//請求成功- (void)requestFinished:(ASIHTTPRequest *)request{ NSDictionary *userInfo = [request userInfo]; id delegate = [userInfo objectForKey:@"target"]; int conTag = [[userInfo objectForKey:@"tag"] intValue]; NSLog(@"\n成功 地址:%@ \n ConnectId = %d 結果 = %@",[[request url] absoluteString],conTag,[request responseString]); NSString *responseString = [request responseString]; // if ([responseString hasPrefix:@"" withString:xmlHeader];// // UseXmlParser *xmlParser = [[UseXmlParser alloc] initWithParserData:[responseString dataUsingEncoding:NSUTF8StringEncoding] target:delegate connectId:conTag];// [xmlParser parser];// [xmlParser release];// }else{ NSLog(@"%@",[responseString JSONValue]); //得到資料來源,通過代理返回 if (delegate && [delegate respondsToSelector:@selector(NetWorkBackConnectID:BackString:WithNetState:)]) { [delegate NetWorkBackConnectID:conTag BackString:responseString WithNetState:0]; } // }}//請求失敗- (void)requestFailed:(ASIHTTPRequest *)request{ NSLog(@"錯誤資訊:%@",[request error]); NSDictionary *userInfo = [request userInfo]; id delegate = [userInfo objectForKey:@"target"];#pragma unused(delegate) int conTag = [[userInfo objectForKey:@"tag"] intValue]; NSLog(@"\n失敗 地址:%@ \n ConnectId = %d 結果 = %@",[[request url] absoluteString],conTag,[request responseString]); if (delegate && [delegate respondsToSelector:@selector(NetWorkBackConnectID:BackDic:WithNetState:)]) { [delegate NetWorkBackConnectID:conTag BackDic:nil WithNetState:0]; } if (delegate && [delegate respondsToSelector:@selector(NetWorkBackConnectID:BackString:WithNetState:)]) { [delegate NetWorkBackConnectID:conTag BackString:@"" WithNetState:0]; } UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"" message:@"資料請求失敗" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil]; [av show]; [av release];}// 判斷是否連網-(BOOL)isConnectNetWork{ BOOL isExistenceNetwork = YES; Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"]; switch ([r currentReachabilityStatus]) { case NotReachable: isExistenceNetwork=NO; NSLog(@"沒有網路"); break; case ReachableViaWWAN: isExistenceNetwork=YES; NSLog(@"正在使用3G網路"); break; case ReachableViaWiFi: isExistenceNetwork=YES; NSLog(@"正在使用wifi網路"); break; } return isExistenceNetwork;}//彈出WiFi- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ if (alertView.tag == 0x9999) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];// exit(0); }}@end
#pragma mark -請求資訊-(void)RentNewsRequest{ NSString *ss = [NSString stringWithFormat:@"szzssw/taxCommon.action?code=1001&pagecode=%d&menucode=0300000000",NewsView.pageCode == 0 ? 1 : NewsView.pageCode]; [[JSNetWork shareNetWork] JSNetWorkWith:100 Body:ss PostBody:nil Delegate:self]; //先充緩衝裡面去讀取 NSString *cachestr=[self readApiCacheFileName:@"地稅新聞列表.txt"]; //只是對上拉資訊,讀取緩衝 if(cachestr.length>0 &&NewsView.pageCode==1){ [self NetWorkBackConnectID:100 BackString:cachestr WithNetState:0]; }}#pragma mark -資料完成資訊- (void)NetWorkBackConnectID:(int)connectID BackString:(NSString *)aBackString WithNetState:(int)netState{ NewsView.aTable.pullTableIsRefreshing=YES; NewsView.aTable.pullTableIsLoadingMore=YES; NewsView.aTable.pullTableIsRefreshing=NO; NewsView.aTable.pullTableIsLoadingMore=NO; if(connectID==100){ NSDictionary *jsonDic=ASDynamicCast(NSDictionary, [aBackString JSONValue]); //根據請求的內容判斷請求是否成功 if (![[jsonDic getStringByKey:@"dealcode"] isEqualToString:@"0000"]) { NSLog(@"請求失敗-->%@",[jsonDic getStringByKey:@"dealmsg"]); return; } //如果是上拉,進行緩衝 if (NewsView.pageCode==1) { [self saveApiCacheFileName:@"地稅新聞列表.txt" textContent:aBackString Append:NO]; } if (NewsView.dataArray.count>0 &&NewsView.pageCode==1) { [NewsView.dataArray removeAllObjects];//向下拉只顯示20條,下拉只顯示就疊加 } NSArray *contentArray=ASDynamicCast(NSDictionary, [aBackString JSONValue])[@"content"]; [NewsView.dataArray addObjectsFromArray:contentArray]; [NewsView.aTable reloadData]; } }