您的位置:首页 > 理论基础 > 计算机网络

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

2014-10-09 16:56 363 查看
#import<Foundation/Foundation.h>
#import"ASIFormDataRequest.h"
#import"Reachability.h"

@protocolNetWorkDelegate;

@interfaceJSNetWord:NSObject<ASIHTTPRequestDelegate>
+(id)ShareNetwork;
-(void)NetWorkWithConnctId:(int)connectidbody:(NSString*)bodyPostBody:(NSString*)PostBodyaDelegate:(id<NetWorkDelegate>)delegate;
@end

@protocolNetWorkDelegate<NSObject>

-(void)NetWorkWithConnectId:(int)connectidaBackString:(NSString*)backStringwithState:(int)state;

@end

#import"JSNetWord.h"

@implementationJSNetWord
+(id)ShareNetwork{
staticdispatch_once_tonceToken;
staticJSNetWord*netWork=nil;
dispatch_once(&onceToken,^{
netWork=[[JSNetWordalloc]init];
});
returnnetWork;
}

//网络请求
-(void)NetWorkWithConnctId:(int)connectidbody:(NSString*)bodyPostBody:(NSString*)PostBodyaDelegate:(id<NetWorkDelegate>)delegate{
if([selfIsConnect]){
UIAlertView*alertview=[[UIAlertViewalloc]initWithTitle:nilmessage:@"请联网"delegate:selfcancelButtonTitle:@"OK"otherButtonTitles:nil];
[alertviewshow];
[alertviewrelease];
if(delegate&&[delegaterespondsToSelector:@selector(NetWorkWithConnectId:aBackString:withState:)]){
[delegateNetWorkWithConnectId:connectidaBackString:nilwithState:1];
}
return;
}
ASIFormDataRequest*Request=[ASIFormDataRequestrequestWithURL:[NSURLURLWithString:@"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=[PostBodycomponentsSeparatedByString:@"&"];
for(NSString*tempinPostBodyArrary){
NSArray*postArray=[tempcomponentsSeparatedByString:@"="];
[RequestsetPostValue:postArray[1]forKey:postArray[2]];
}
//封装参数
NSString*cid=[NSStringstringWithFormat:@"%zi",connectid];
Request.userInfo=@{@"cid":cid,@"delegate":delegate};
[RequeststartAsynchronous];
}

#pragmamark-ASIHttpRequestdelegate
-(void)requestStarted:(ASIHTTPRequest*)request{
//可以加入toast
}

-(void)requestFinished:(ASIHTTPRequest*)request{
NSDictionary*dic=request.userInfo;
intconnectid=[dic[@"cid"]intValue];
id<NetWorkDelegate>delegate=dic[@"delegate"];
if(delegate&&[delegaterespondsToSelector:@selector(NetWorkWithConnectId:aBackString:withState:)]){
[delegateNetWorkWithConnectId:connectidaBackString:[requestresponseString]withState:1];
}

}

-(void)requestFailed:(ASIHTTPRequest*)request{
NSDictionary*dic=request.userInfo;
intconnectid=[dic[@"cid"]intValue];
id<NetWorkDelegate>delegate=dic[@"delegate"];
NSLog(@"错误原因:-->%@",request.error.localizedDescription);
if(delegate&&[delegaterespondsToSelector:@selector(NetWorkWithConnectId:aBackString:)]){
[delegateNetWorkWithConnectId:connectidaBackString:[requestresponseString]withState:1];
}
UIAlertView*alertview=[[UIAlertViewalloc]initWithTitle:@"提示"message:@"请求失败"delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil];
[alertviewshow];
[alertviewrelease];
}

//判断是否联网
-(BOOL)IsConnect{
BOOLIsCon=NO;
Reachability*r=[ReachabilityreachabilityWithHostName:@"www.baidu.com"];
switch([rcurrentReachabilityStatus]){
caseNotReachable:
NSLog(@"notnetwork");
IsCon=NO;
break;
caseReachableViaWiFi:
NSLog(@"wifi");
IsCon=YES;
break;
caseReachableViaWWAN:
NSLog(@"3g");
IsCon=YES;
break;

default:
break;
}
returnIsCon;
}

@end


封装上下拉tableview.

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

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

#import<UIKit/UIKit.h>
#import"PullTableView.h"

@interfaceJSContentView:UIView<UITableViewDataSource,UITableViewDelegate,PullTableViewDelegate>

-(id)initWithFrame:(CGRect)framerequestSEL:(SEL)aselectoraDelegate:(id)delegate;
@property(nonatomic,assign)intPagecode;
@property(nonatomic,readonly)PullTableView*tableview;
@property(nonatomic,retain)NSMutableArray*mydata;
@end

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

@interfaceJSContentView()
{
SELselector;
iddelegate;
}

@end

@implementationJSContentView

#pragmamark-初始化
-(id)initWithFrame:(CGRect)framerequestSEL:(SEL)aselectoraDelegate:(id)adelegate{
self=[superinitWithFrame:frame];
if(self){
self.mydata=[NSMutableArrayarray];
_tableview=[[PullTableViewalloc]initWithFrame:self.boundsstyle:UITableViewStylePlain];
_tableview.delegate=self;
_tableview.dataSource=self;
_tableview.pullDelegate=self;

//设置pulltableview的背景色
_tableview.pullBackgroundColor=[UIColorclearColor];
_tableview.pullTextColor=[UIColorblackColor];

[selfaddSubview:_tableview];
selector=aselector;
delegate=adelegate;

//第一次加载的时候默认要刷新。
if(!self.tableview.pullTableIsRefreshing){
self.tableview.pullTableIsRefreshing=YES;
if(delegate&&[delegaterespondsToSelector:selector]){
[delegateperformSelector:selector];
}
}
self.tableview.pullTableIsLoadingMore=NO;
}
returnself;
}

-(void)dealloc
{
[_mydatarelease];
[superdealloc];
}

#pragmamark-tableviewdataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView{
return1;
}

-(NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section{
returnself.mydata.count;
}

-(UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath{
staticNSString*cellIdentify=@"myCell";
MyCell*cell=[tableViewdequeueReusableCellWithIdentifier:cellIdentify];
if(cell==nil){
cell=[[[MyCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellIdentify]autorelease];
}
NSDictionary*dic=self.mydata[indexPath.row];
cell.value=dic;
returncell;
}

#pragmamark-tableviewdelegate
-(CGFloat)tableView:(UITableView*)tableViewheightForRowAtIndexPath:(NSIndexPath*)indexPath{
return80;
}

-(void)tableView:(UITableView*)tableViewdidSelectRowAtIndexPath:(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"

@interfaceViewController:UIViewController<NetWorkDelegate>

@end

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

@interfaceViewController()
{
JSContentView*newView;
}

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

@implementationViewController

-(void)viewDidLoad
{
[superviewDidLoad];
newView=[[JSContentViewalloc]initWithFrame:self.view.boundsrequestSEL:@selector(RequestData)aDelegate:self];
[self.viewaddSubview:newView];
[newViewrelease];
//如果开始启用缓存
//NSString*cache=[selfreadApiCacheFileName:@"1.txt"];
//if(cache.length>0&&newView.Pagecode<=1){
//[selfNetWorkWithConnectId:100aBackString:cachewithState:0];
//}

}

-(void)RequestData{
NSString*url=[NSStringstringWithFormat:@"http://61.177.61.252/szzssw/taxCommon.action?code=1001&pagecode=%zi&menucode=3300000000",newView.Pagecode==0?1:newView.Pagecode];
//请求数据,重新刷新数据
[[JSNetWordShareNetwork]NetWorkWithConnctId:100body:urlPostBody:nilaDelegate:self];
//先从缓存中读取
NSString*cache=[selfreadApiCacheFileName:@"1.txt"];

if(cache.length>0&&newView.Pagecode==1){
[selfNetWorkWithConnectId:100aBackString:cachewithState:0];
}

}

#pragmamark-networkdelegate
-(void)NetWorkWithConnectId:(int)connectidaBackString:(NSString*)backStringwithState:(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=[backStringJSONValue];
NSString*dealcode=dic[@"dealcode"];
if(![dealcodeisEqualToString:@"0000"]){
return;
}

if(newView.Pagecode==1){
[selfsaveApiCacheFileName:@"1.txt"textContent:backStringAppend:NO];
}
if(newView.Pagecode==1&&newView.mydata.count>0){
[newView.mydataremoveAllObjects];
}
NSArray*data=dic[@"content"];
[newView.mydataaddObjectsFromArray:data];
[newView.tableviewreloadData];

}
}


-(void)EnterDetailPage:(NSString*)row{
intr=[rowintValue];
NSDictionary*dic=newView.mydata[r];
NSLog(@"%@",dic[@"title"]);
//可以创建指定controlview。
//ViewController*vc=[[ViewControlleralloc]init];
//......
}
-(void)viewDidUnload{
[superviewDidUnload];
self.dataArray=nil;
}

-(void)dealloc
{
[_dataArrayrelease];
[superdealloc];
}

@end


其中自定义cell

#import<UIKit/UIKit.h>

@interfaceMyCell:UITableViewCell

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

#import"MyCell.h"
#defineKTitleFont15
#defineKFont12
#defineKpadding10

@interfaceMyCell(){
UILabel*titleLb;
UILabel*Contetlb;
UILabel*dataLb;
}

@end

@implementationMyCell

-(id)initWithStyle:(UITableViewCellStyle)stylereuseIdentifier:(NSString*)reuseIdentifier
{
self=[superinitWithStyle:stylereuseIdentifier:reuseIdentifier];
if(self){
titleLb=[UILabelLabWithFrame:CGRectZerotext:@""textColor:[UIColorredColor]textAlign:NSTextAlignmentLeftfont:[UIFontsystemFontOfSize:KTitleFont]];
//Contetlb=[UILabelLabWithFrame:CGRectZerotext:@""textColor:[UIColorblackColor]textAlign:NSTextAlignmentRightfont:[UIFontsystemFontOfSize:KFont]];
dataLb=[UILabelLabWithFrame:CGRectZerotext:@""textColor:[UIColorblackColor]textAlign:NSTextAlignmentLeftfont:[UIFontsystemFontOfSize:KFont]];
[self.contentViewaddSubview:titleLb];

[self.contentViewaddSubview:dataLb];
}
returnself;
}
-(void)setValue:(NSDictionary*)value{
if(_value!=value){
[_valuerelease];
_value=[valueretain];
titleLb.text=value[@"title"];
dataLb.text=value[@"time"];
}
}
-(void)layoutSubviews{
[superlayoutSubviews];
CGFloatwidth=self.contentView.bounds.size.width;
CGFloatheight=self.contentView.bounds.size.height*0.5f;
CGFloattitlex=Kpadding;
CGFloattitley=Kpadding;
CGFloattitlew=width-2*Kpadding;
CGFloattitleh=height;
titleLb.frame=CGRectMake(titlex,titley,titlew,titleh);

CGFloatdx=titlex;
CGFloatdy=titley+titleh;
CGFloatdw=titlew;
CGFloatdh=height-Kpadding;
dataLb.frame=CGRectMake(dx,dy,dw,dh);

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: