代码改变世界

ios中封装网络和tableview的综合运用

2013-08-01 17:22  甘超波  阅读(3577)  评论(0编辑  收藏  举报

1:封装网络请求 类

#import <Foundation/Foundation.h>
#import "ASIFormDataRequest.h"
#import "Reachability.h"

@protocol NetWorkDelegate;

@interface JSNetWord : NSObject<ASIHTTPRequestDelegate>
+(id)ShareNetwork;
-(void)NetWorkWithConnctId:(int)connectid body:(NSString *)body PostBody:(NSString *)PostBody aDelegate:(id<NetWorkDelegate>)delegate;
@end

@protocol NetWorkDelegate <NSObject>

-(void)NetWorkWithConnectId:(int)connectid  aBackString:(NSString *)backString withState:(int) state;

@end

#import "JSNetWord.h"

@implementation JSNetWord
+(id)ShareNetwork{
    static dispatch_once_t onceToken;
    static JSNetWord *netWork=nil;
    dispatch_once(&onceToken, ^{
        netWork=[[JSNetWord alloc] init];
    });
    return netWork;
}

//网络请求
-(void)NetWorkWithConnctId:(int)connectid body:(NSString *)body PostBody:(NSString *)PostBody aDelegate:(id<NetWorkDelegate>)delegate{
    if([self IsConnect]){
        UIAlertView *alertview=[[UIAlertView alloc] initWithTitle:nil message:@"请联网" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alertview show];
        [alertview release];
        if(delegate && [delegate respondsToSelector:@selector(NetWorkWithConnectId:aBackString:withState:)]){
          [delegate NetWorkWithConnectId:connectid aBackString:nil withState:1];
        }
        return;
    }
    ASIFormDataRequest *Request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://61.177.61.252/szzssw/taxCommon.action?code=1001&pagecode=1&menucode=3300000000"]];
    Request.timeOutSeconds=30;
    Request.requestMethod=@"POST";
    Request.delegate=self;
    NSArray *PostBodyArrary=[PostBody componentsSeparatedByString:@"&"];
    for(NSString *temp in PostBodyArrary){
        NSArray *postArray=[temp componentsSeparatedByString:@"="];
        [Request setPostValue:postArray[1] forKey:postArray[2]];
    }
    //封装参数
    NSString *cid=[NSString stringWithFormat:@"%zi",connectid];
    Request.userInfo=@{@"cid":cid,@"delegate":delegate};
    [Request startAsynchronous];
}


#pragma mark -ASIHttpRequest delegate
-(void)requestStarted:(ASIHTTPRequest *)request{
    //可以加入 toast
}

-(void)requestFinished:(ASIHTTPRequest *)request{
    NSDictionary *dic=request.userInfo;
   int connectid= [dic[@"cid"] intValue];
    id<NetWorkDelegate> delegate=dic[@"delegate"];
    if (delegate &&[delegate respondsToSelector:@selector(NetWorkWithConnectId:aBackString:withState:)]) {
        [delegate NetWorkWithConnectId:connectid aBackString:[ request responseString] withState:1];
    }
    
}

-(void)requestFailed:(ASIHTTPRequest *)request{
    NSDictionary *dic=request.userInfo;
    int connectid= [dic[@"cid"] intValue];
    id<NetWorkDelegate> delegate=dic[@"delegate"];
    NSLog(@"错误原因:-->%@",request.error.localizedDescription);
    if(delegate &&[delegate respondsToSelector:@selector(NetWorkWithConnectId:aBackString:)]){
        [delegate NetWorkWithConnectId:connectid aBackString:[request responseString] withState:1];
    }
    UIAlertView *alertview=[[UIAlertView alloc] initWithTitle:@"提示" message:@"请求失败" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alertview show];
    [alertview release];
}

//判断是否联网
-(BOOL)IsConnect{
    BOOL IsCon=NO;
    Reachability *r=[Reachability reachabilityWithHostName:@"www.baidu.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            NSLog(@"not network");
            IsCon=NO;
            break;
         case ReachableViaWiFi:
            NSLog(@"wifi");
            IsCon=YES;
            break;
            case ReachableViaWWAN:
            NSLog(@"3g");
            IsCon=YES;
            break;
            
        default:
            break;
    }
    return IsCon;
}

@end

封装上下拉tableview .

配置步骤:英文原文和类库下载地址:https://github.com/emreberge/EGOTableViewPullRefresh

  • 添加 QuartzCore.framework 到你的工程中。
  • 将 EGOTableViewPullRefresh 拖到你的工程目录下。
  • 查看 PullTableView.h 文件可用的属性。
  • 添加一个PullTableView 到你代码中,实现PullTableViewDelegate委托方法
#import <UIKit/UIKit.h>
#import "PullTableView.h"

@interface JSContentView : UIView<UITableViewDataSource,UITableViewDelegate,PullTableViewDelegate>

-(id)initWithFrame:(CGRect)frame requestSEL:(SEL)aselector aDelegate:(id)delegate;
@property(nonatomic,assign)int Pagecode;
@property(nonatomic,readonly)PullTableView *tableview;
@property(nonatomic,retain)NSMutableArray *mydata;
@end


#import "JSContentView.h"
#import "MyCell.h"

@interface JSContentView ()
{
    SEL selector;
    id delegate;
}

@end


@implementation JSContentView

#pragma mark -初始化
-(id)initWithFrame:(CGRect)frame requestSEL:(SEL)aselector aDelegate:(id)adelegate{
    self=[super initWithFrame:frame];
    if(self){
        self.mydata=[NSMutableArray array];
        _tableview =[[PullTableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
        _tableview.delegate=self;
        _tableview.dataSource=self;
        _tableview.pullDelegate=self;
        
        //设置pulltableview 的背景色
        _tableview.pullBackgroundColor=[UIColor clearColor];
        _tableview.pullTextColor=[UIColor blackColor];
        
        [self addSubview:_tableview];
        selector=aselector;
        delegate=adelegate;
        
        //第一次加载的时候默认要刷新。
        if(!self.tableview.pullTableIsRefreshing){
            self.tableview.pullTableIsRefreshing=YES;
            if (delegate&&[delegate respondsToSelector:selector]) {
                [delegate performSelector:selector];
            }
        }
        self.tableview.pullTableIsLoadingMore=NO;
    }
    return self;
}

- (void)dealloc
{
    [_mydata release];
    [super dealloc];
}

#pragma mark -tableview dataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.mydata.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   static NSString *cellIdentify=@"myCell";
    MyCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (cell==nil) {
        cell=[[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify] autorelease];
    }
   NSDictionary *dic=self.mydata[indexPath.row];
   cell.value=dic;
   return cell;
}

#pragma mark -tableview delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


 


    NSString *str = [NSStringstringWithFormat:@"%d",indexPath.row];


    if(self.delegate && [self.delegate respondsToSelector:@selector(EnterDetailPage:)]){


        [self.delegate performSelector:@selector(EnterDetailPage:) withObject:str];


    }


}

 

在viewcontroller里面运用起来。

#import <UIKit/UIKit.h>

#import "JSContentView.h"
#import "JSNetWord.h"

@interface ViewController : UIViewController<NetWorkDelegate>

@end

===========
#import "ViewController.h"
#import "MyCell.h"

@interface ViewController ()
{
    JSContentView *newView;
}

@property(nonatomic,retain)NSMutableArray *dataArray;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    newView=[[JSContentView alloc] initWithFrame:self.view.bounds requestSEL:@selector(RequestData) aDelegate:self];
    [self.view addSubview:newView];
    [newView release];
    //如果开始启用缓存
//    NSString *cache=[self readApiCacheFileName:@"1.txt"];
//    if (cache.length>0 &&newView.Pagecode<=1) {
//          [self NetWorkWithConnectId:100 aBackString:cache withState:0];
//    }
 
 
   
}

-(void)RequestData{
    NSString *url=[NSString stringWithFormat:@"http://61.177.61.252/szzssw/taxCommon.action?code=1001&pagecode=%zi&menucode=3300000000",newView.Pagecode==0?1:newView.Pagecode];
    //请求数据,重新刷新数据
    [[JSNetWord ShareNetwork] NetWorkWithConnctId:100 body:url PostBody:nil aDelegate:self];
    //先从缓存中读取
    NSString *cache=[self readApiCacheFileName:@"1.txt"];
    
    if (cache.length>0 &&newView.Pagecode==1) {
        [self NetWorkWithConnectId:100 aBackString:cache withState:0];
    }

}





#pragma mark -network delegate
-(void)NetWorkWithConnectId:(int)connectid aBackString:(NSString *)backString withState:(int)state{
    if(connectid==100){
//1:代表网络 0代表缓存
if (newView.Pagecode<=1 && state==1) { newView.tableview.pullTableIsRefreshing=NO; } if (newView.Pagecode>1) { newView.tableview.pullTableIsLoadingMore=NO; } NSDictionary *dic=[backString JSONValue]; NSString *dealcode=dic[@"dealcode"]; if (![dealcode isEqualToString:@"0000"]) { return; } if (newView.Pagecode==1) { [self saveApiCacheFileName:@"1.txt" textContent:backString Append:NO]; } if (newView.Pagecode==1 &&newView.mydata.count>0) { [newView.mydata removeAllObjects]; } NSArray *data=dic[@"content"]; [newView.mydata addObjectsFromArray:data]; [newView.tableview reloadData]; } }

-(void)EnterDetailPage:(NSString *)row{


    int r=[row intValue];


    NSDictionary *dic=newView.mydata[r];


    NSLog(@"%@",dic[@"title"]);


    //可以创建指定controlview


//    ViewController *vc=[[ViewController alloc] init];


//    ......


}

-(void)viewDidUnload{
    [super viewDidUnload];
    self.dataArray=nil;
}

- (void)dealloc
{
    [_dataArray release];
    [super dealloc];
}

@end

其中自定义cell

#import <UIKit/UIKit.h>

@interface MyCell : UITableViewCell

@property(nonatomic,retain)NSDictionary *value;
@end


#import "MyCell.h"
#define KTitleFont 15
#define KFont 12
#define Kpadding 10

@interface MyCell (){
    UILabel *titleLb;
    UILabel *Contetlb;
    UILabel *dataLb;
}

@end

@implementation MyCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        titleLb=[UILabel LabWithFrame:CGRectZero text:@"" textColor:[UIColor redColor] textAlign:NSTextAlignmentLeft font:[UIFont systemFontOfSize:KTitleFont]];
       // Contetlb=[UILabel LabWithFrame:CGRectZero text:@"" textColor:[UIColor blackColor] textAlign:NSTextAlignmentRight font:[UIFont systemFontOfSize:KFont]];
        dataLb=[UILabel LabWithFrame:CGRectZero text:@"" textColor:[UIColor blackColor] textAlign:NSTextAlignmentLeft font:[UIFont systemFontOfSize:KFont]];
        [self.contentView addSubview:titleLb];

        [self.contentView addSubview:dataLb];
    }
    return self;
}
-(void)setValue:(NSDictionary *)value{
    if(_value!=value){
        [_value release];
        _value=[value retain];
        titleLb.text=value[@"title"];
        dataLb.text=value[@"time"];
    }
}
-(void)layoutSubviews{
    [super layoutSubviews];
    CGFloat width=self.contentView.bounds.size.width;
    CGFloat height=self.contentView.bounds.size.height*0.5f;
    CGFloat titlex=Kpadding;
    CGFloat titley=Kpadding;
    CGFloat titlew=width-2*Kpadding;
    CGFloat titleh=height;
    titleLb.frame=CGRectMake(titlex, titley, titlew, titleh);
    
    CGFloat dx=titlex;
    CGFloat dy=titley+titleh;
    CGFloat dw=titlew;
    CGFloat dh=height-Kpadding;
    dataLb.frame=CGRectMake(dx, dy, dw, dh);
    
}

@end

 

 地址 http://pan.baidu.com/share/link?shareid=1603134617&uk=923776187