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

#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[email protected]{@"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
时间: 2024-08-28 07:57:09

ios中封装网络和tableview的综合运用的相关文章

ios中封装网络请求类

ios中封装网络请求类 #import "JSNetWork.h" //asiHttpRequest #import "ASIFormDataRequest.h" //xml 的解析 #import "UseXmlParser.h" //判断是否联网 #import "Reachability.h" //sbJson,判断json的解析 #import "JSON.h" @implementation JS

iOS中从网络获取数据的几种方法的比较

IOS中获取网络数据一般有三种:1.NSURLCondition(已过时) 2.NSURLSession  3.三方库AFNetWorking NSURLSession 是苹果对NSULRCondition的替代品,NSURLSession比NSURLCondition多了 1.可配置的数据信息NSURLSessionConfiguration,NSURLSessionConfiguration使你可以设置你要请求的数据,通常的设置如缓存,也可以使用默认的配置信息defaultCongurati

IOS中的网络编程

在移动互联网时代,几乎所有应用都需要用到网络下载,比如图片的加载,音乐的下载,安装包的下载,等等,下面我们来看看如何进行下载 一.文件的下载我们用get来请求数据,并对请求的二进制数据进行解析存入文件,首先我们先引入一个第三方进度条 ,并且进行初始化 - (void)viewDidLoad { [super viewDidLoad]; //设置背景色 self.view.backgroundColor=[UIColor greenColor]; //引入第三方进度条 self.da=[[DACi

IOS中的网络请求

使用NSURLConnection的网络请求,最好定义一个类方法,在主线程中直接调用类方法获取请求到的网络数据 //构建类方法--请求网络 + (void)requestData:(NSString *)urlStr httpMethod:(NSString *)method params:(NSMutableDictionary *)params comletionHandle:(void (^)(id result))block { //1.构建URL urlStr = [BASE_URL

iOS中相册-用一个tableView区分照片和video

[objc] view plaincopyprint? <span style="font-size:18px;"> #import "ViewController.h" @interface ViewController () @property(nonatomic,strong)UITableView *tableView; @property(nonatomic,strong)NSMutableArray *assets;// 照片数组 @prop

ios 中scrollview上面嵌套tableView,左右滑动出现数据多次刷新的问题

注意scrollView左右滑动时不要刷新数据,刚进来时一次性请求所有数据 红包纪录和房源信息可以左右滑动和点击,tableView可以上下滑动,图片部分个人信息只刷新一次. 界面布局如下

iOS中打开网络交互的方式

<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>

iOS封装网络请求

iOS中经常会有网络请求,可以把它封装起来,方便使用: 网络封装请求类: .h文件: #import <Foundation/Foundation.h> @interface NetHandler : NSObject //无返回值,根据网络请求 的特点,不同的地方就是请求的地址和分析数据的方式不一样,就是把这两部分分别作为方法参数 + (void)getDataWithUrl:(NSString *)str complietion:(void(^)(NSData *data))block;

iOS开发项目篇—35封装网络请求

iOS开发项目篇—35封装网络请求 一.简单说明 1.分析项目对网路请求(AFN框架)的依赖 项目中,多个控制器都使用了AFN框架发送网络请求,如果AFN2.0存在重大BUg,或者是升级至3.0版本,那么对于整个项目都是及其危险的,所有用到AFN的地方都需要做出相应的修改. 另外,如果现在要求不再使用AFN框架,而是使用一个新的框架,那么有关AFN的依赖所关联的所有代码都需要重新来过. 如果把afn这个第三方框架从项目中删除的话,那么项目就相当于作废了,这就是项目对第三方框架的强依赖的体现. 说