代码改变世界

ios中封装网络请求类

2013-07-25 08:50  甘超波  阅读(11204)  评论(0编辑  收藏  举报
#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:@"<?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: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];


    }
    
}