#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:];
} return;
} if ([bodyString hasPrefix:@"http"] == NO) {
bodyString = [NSString stringWithFormat:@"%@/%@",HTTPURLPREFIX,bodyString];
} ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:bodyString]];
[request setDelegate:self];
request.timeOutSeconds = ;
[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:] forKey:[bb objectAtIndex:]];
} //传递参数
[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:@"<?xml"]) {
// responseString = [responseString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
// responseString = [responseString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
// responseString = [responseString stringByReplacingOccurrencesOfString:@"<?xml version=\"1.0\" encoding=\"GBK\"?>" 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:];
} // }
} //请求失败
- (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:];
}
if (delegate && [delegate respondsToSelector:@selector(NetWorkBackConnectID:BackString:WithNetState:)]) {
[delegate NetWorkBackConnectID:conTag BackString:@"" WithNetState:];
}
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 == ? : NewsView.pageCode];
[[JSNetWork shareNetWork] JSNetWorkWith: Body:ss PostBody:nil Delegate:self];
//先充缓存里面去读取
NSString *cachestr=[self readApiCacheFileName:@"地税新闻列表.txt"];
//只是对上拉信息,读取缓存
if(cachestr.length> &&NewsView.pageCode==){
[self NetWorkBackConnectID: BackString:cachestr WithNetState:];
}
} #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==){ NSDictionary *jsonDic=ASDynamicCast(NSDictionary, [aBackString JSONValue]);
//根据请求的内容判断请求是否成功
if (![[jsonDic getStringByKey:@"dealcode"] isEqualToString:@""]) {
NSLog(@"请求失败-->%@",[jsonDic getStringByKey:@"dealmsg"]);
return;
} //如果是上拉,进行缓存
if (NewsView.pageCode==) {
[self saveApiCacheFileName:@"地税新闻列表.txt" textContent:aBackString Append:NO];
}
if (NewsView.dataArray.count> &&NewsView.pageCode==) {
[NewsView.dataArray removeAllObjects];//向下拉只显示20条,下拉只显示就叠加
} NSArray *contentArray=ASDynamicCast(NSDictionary, [aBackString JSONValue])[@"content"];
[NewsView.dataArray addObjectsFromArray:contentArray];
[NewsView.aTable reloadData]; } }