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

1、封装网络请求类

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

1-1 、接口文件

@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


1-2、实现文件

#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: IsCon = NO; break;
        case ReachableViaWiFi: IsCon = YES; break;
        case ReachableViaWWAN: IsCon = YES; break;
        default: break;
    }
    return IsCon;
}

@end


2、封装上下拉tableview

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

1、添加 QuartzCore.framework到你的工程中。

2、将 EGOTableViewPullRefresh拖到你的工程目录下。

3、查看 PullTableView.h文件可用的属性。

4、添加一个PullTableView到你代码中,实现PullTableViewDelegate委托方法


2-1、接口文件

#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


2-2、实现文件

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


3、使用

3-1、接口文件

#import <UIKit/UIKit.h>
#import "JSContentView.h"
#import "JSNetWord.h"

@interface ViewController : UIViewController <NetWorkDelegate>

@end


3-2、实现文件

#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 (connected == 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


4、自定义cell

4-1、接口文件

#import <UIKit/UIKit.h>

@interface MyCell : UITableViewCell

@property(nonatomic, retain) NSDictionary *value;

@end


4-2、实现文件

#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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值