ios中封裝網路和tableview的綜合運用

來源:互聯網
上載者:User

ios中封裝網路和tableview的綜合運用

#import #import "ASIFormDataRequest.h"#import "Reachability.h"@protocol NetWorkDelegate;@interface JSNetWord : NSObject+(id)ShareNetwork;-(void)NetWorkWithConnctId:(int)connectid body:(NSString *)body PostBody:(NSString *)PostBody aDelegate:(id)delegate;@end@protocol NetWorkDelegate -(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)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 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 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 #import "PullTableView.h"@interface JSContentView : UIView-(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.delegaterespondsToSelector:@selector(EnterDetailPage:)]){

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

}

}

 

在viewcontroller裡面運用起來。

#import #import "JSContentView.h"#import "JSNetWord.h"@interface ViewController : UIViewController@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 @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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.