iOS 网络请求类封装

转载 2015年11月18日 00:24:10
转载自:http://www.cnblogs.com/gcb999/p/3213601.html
感谢

#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];


    }
    
}

iOS网络请求 post同步异步封装demo

  • 2015年11月18日 22:56
  • 38KB
  • 下载

iOS 【OC 封装网络请求业务类(AFHTTPRequestOperationManager 废弃)】

对于一些常用的第三方,他们常用,自然作者也会经常更新。这样一来或许会出现“牵一发而动全身的局面”。一旦一个方法、某个类出现了名称或者功能上的改动,那么如果在项目中多处地方引用了这个不稳定的第三方,是很...

ios中封装网络请求类

#import "JSNetWork.h" //asiHttpRequest #import "ASIFormDataRequest.h" //xml 的解析 #import "UseXmlParse...

ios中封装网络请求类

ios中封装网络请求类 #import "JSNetWork.h" //asiHttpRequest #import "ASIFormDataRequest.h" //xml 的解析 #import...

iOS 自己封装的网络请求,json解析的类

基本上所有的APP都会涉及网络这块,不管是用AFNetWorking还是自己写的http请求,整个网络框架的搭建很重要。 楼主封装的网络请求类,包括自己写的http请求和AFNetWorking的请...

IOS:MKNetworkKit的网络请求(使用封装好的类)

既然看到本文章,至少你已经对MKNetworkKit不是太陌生了。那就废话少说,直接上代码。 yi...

iOS开发—封装网络请求工具类

一.封装的好处 可以降低网络请求方法与Controller 的耦合度,即使网络请求使用的第三方框架发生不兼容、错误等问题从而想换框架时,也不用到每个控制器里面改代码建立单例工具类,方便管理优化代...

iOS项目中的网络请求和上下拉刷新封装

现在的项目中不可避免的要使用到网络请求,而且几乎所有软件都有上下拉刷新功能,所以我在此对我的项目进行一个网络请求的封装和上下拉刷新的封装,如果有哪里不对,或更优的地方请在下面留言。附上展示效果项目的G...

iOS 网络请求失败View封装

封装一个NoData的View方便在网络请求失败时调用 1新建一个继承UIView的类:XSNoDataView 头文件里 #import typedef void (^ButtonBlo...
  • bitcser
  • bitcser
  • 2017年01月03日 15:35
  • 807

iOS开发——POST异步网络请求自行封装

IOS中有许多网络请求的函数,同步的,异步的,通过delegate异步回调的。   在做一个项目的时候,上网看了很多别人的例子,发现都没有一个简单的,方便的异步请求的封装例子。我这里要给出的封装...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:iOS 网络请求类封装
举报原因:
原因补充:

(最多只允许输入30个字)