Hi,本篇文章主要讲解如何利用服务端,获取json数据并且动态显示到UITableView之中;
分别思路逻辑有以下:
1.建立该需要项目文件,如:PurchaseView.h(样式),PurchaseController.h(逻辑);
2.使用的AFNetworking,请求服务端数据框架(记得导入该文件头部);
3.定义该展示样式:如:名字,地址,产品编号...;
4:动态显示到UITableView上;
5:字典类型和JSON的相互转换,时间戳的转换,List数组的添加模型;
1.PurchaseView.h(样式文件)
#import <UIKit/UIKit.h>
@interface PurchaseView : UITableViewCell
@property(strong,nonatomic) UIScrollView *mslView;
@property(strong,nonatomic) UITableView *tabView;
@property(strong,nonatomic) UILabel *deviceName;//设备名字
@property(strong,nonatomic) UILabel *deviceAddre;//设备地址
@property(strong,nonatomic) UILabel *runTime;//运行时间
@property(strong,nonatomic) UILabel *currency;//货币
@property(strong,nonatomic) UILabel *aggregate;//总金额
@end
2.PurchaseView.m
#import "PurchaseView.h"
#ifdef __OBJC__
//define this constant if you want to use Masonry without the 'mas_' prefix
#define MAS_SHORTHAND
//define this constant if you want to enable auto-boxing for default syntax
#define MAS_SHORTHAND_GLOBALS
#import "Masonry.h"
#endif
@implementation PurchaseView
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if(self){
UIView *mainView = [[UIView alloc] init];
mainView.layer.cornerRadius = 8;
mainView.layer.shadowColor = [UIColor grayColor].CGColor;// 阴影的颜色
mainView.layer.shadowRadius = 3;// 阴影扩散的范围控制
mainView.layer.shadowOffset = CGSizeMake(1, 1);// 阴影的范围
//边框宽
mainView.layer.borderWidth = 2;
//边框颜色
mainView.layer.borderColor = [[UIColor grayColor] CGColor];
[self addSubview:mainView];
[mainView makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self).offset(10);
make.left.equalTo(self).offset(10);
make.right.equalTo(self).offset(-10);
make.height.equalTo(@150);
}];
//显示设备名称
self.deviceName = [[UILabel alloc] init];
self.deviceName.textColor = [UIColor grayColor];
self.deviceName.font = [UIFont fontWithName:@"Helvetica-Bold" size:22];
self.deviceName.text=@"TMW022";
self.deviceName.textAlignment = NSTextAlignmentCenter;
[mainView addSubview:self.deviceName];
[self.deviceName makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(mainView).offset(10);
make.left.equalTo(mainView).offset(10);
make.height.equalTo(@25);
}];
//显示设备地址
self.deviceAddre = [[UILabel alloc] init];
self.deviceAddre.textColor = [UIColor grayColor];
self.deviceAddre.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];
self.deviceAddre.textAlignment = NSTextAlignmentCenter;
[mainView addSubview:self.deviceAddre];
[self.deviceAddre makeConstraints:^(MASConstraintMaker *make){
make.bottom.equalTo(mainView).offset(-10);
make.left.equalTo(mainView).offset(10);
make.height.equalTo(@25);
}];
//货币方式
self.currency = [[UILabel alloc] init];
self.currency.textColor = [UIColor grayColor];
self.currency.font = [UIFont fontWithName:@"Helvetica-Bold" size:14];
self.currency.textAlignment = NSTextAlignmentLeft;
[mainView addSubview:self.currency];
[self.currency makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self.deviceName).offset(40);
make.right.equalTo(mainView).offset(-10);
make.left.equalTo(mainView).offset(10);
make.height.equalTo(@25);
}];
//显示运行时间
self.runTime = [[UILabel alloc] init];
self.runTime.textColor = [UIColor grayColor];
self.runTime.font = [UIFont fontWithName:@"Helvetica-Bold" size:14];
self.runTime.textAlignment = NSTextAlignmentRight;
[mainView addSubview:self.runTime];
[self.runTime makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self.deviceName).offset(40);
make.right.equalTo(mainView).offset(-10);
make.left.equalTo(mainView).offset(10);
make.height.equalTo(@25);
}];
//总金额
self.aggregate = [[UILabel alloc] init];
self.aggregate.textColor = [UIColor grayColor];
self.aggregate.font = [UIFont fontWithName:@"Helvetica-Bold" size:14];
self.aggregate.textAlignment = NSTextAlignmentLeft;
[mainView addSubview:self.aggregate];
[self.aggregate makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self.currency).offset(35);
make.right.equalTo(mainView).offset(-10);
make.left.equalTo(mainView).offset(10);
make.height.equalTo(@25);
}];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
@end
3.PurchaseController.h(逻辑文件)
#import <UIKit/UIKit.h>
#import "PurchaseView.h"
#import "BaseTableViewController.h"
#import "CommonUtil.h"
#import "PurchaseModel.h"
#import "PseDetailsController.h"
//#import "MJExtension.h"
@interface PurchaseController : BaseTableViewController
//@property(strong,nonatomic) PurchaseView * purchView;
@property(nonatomic,strong) PurchaseModel *PurchaseModel;
@property(nonatomic,strong) NSMutableArray *dataList;
@property(nonatomic,strong) NSMutableArray *dataListTemp;
@property(nonatomic,strong) CommonUtil *commonUtil;
//@property(nonatomic,strong) MBProgressHUD *hud;
@end
4.PurchaseController.m
#import "PurchaseController.h"
@interface PurchaseController ()<PurModelDelegate,UITableViewDataSource, UITableViewDelegate>
@end
@implementation PurchaseController
- (void)viewDidLoad {
[super viewDidLoad];
[self initData];
self.view.backgroundColor = [UIColor whiteColor];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//得到wifi数据
[self.PurchaseModel getWifiData];
}
-(void)initData{
UIView *view = [[UIView alloc] init];
self.tableView.tableFooterView = view;
self.tableView.separatorStyle = NO;//隐藏分割线
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self getDataList];
[self getWfModel];
self.PurchaseModel.delegate = self;
}
-(PurchaseModel*)getWfModel{
if(self.PurchaseModel==nil){
self.PurchaseModel = [[PurchaseModel alloc] init];
}
return self.PurchaseModel;
}
-(NSMutableArray *)getDataList{
if(self.dataList==nil){
self.dataList = [NSMutableArray array];
}
return self.dataList;
}
/*
代理
*/
//请求成功的代理
-(void)getDataSuccess:(NSArray *) list{
self.dataList = [NSMutableArray arrayWithArray:list];
[self.tableView reloadData];
}
//请求失败的代理
-(void)getDataFail:(NSString *) message{
NSLog(@"失败%@",message);
}
//定义列的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 170;//tableview列表高度
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.dataList.count;//返回的列表长度
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifiter = @"WifiCellIdentifiter";
PurchaseView *PurCell= [tableView dequeueReusableCellWithIdentifier:cellIdentifiter];
if (PurCell == nil) {
PurCell = [[PurchaseView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifiter];
}
NSUInteger row = [indexPath row];
if(row<self.dataList.count){
Signals *signals = [[Signals alloc] init];
signals = [self.dataList objectAtIndex:row];
PurCell.deviceAddre.text = signals.supplier_Name;
PurCell.deviceName.text = signals.pono;
NSString *timeStampString = signals.addDate;
// iOS 生成的时间戳是10位
NSTimeInterval interval =[timeStampString doubleValue] / 1000.0;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateString = [formatter stringFromDate: date];
PurCell.runTime.text = dateString;
NSString *currencyName = [NSString stringWithFormat:@"货币:%@",signals.currencyName];
NSString *priceS = [NSString stringWithFormat:@"总金额:%@",signals.priceS];
PurCell.currency.text = currencyName;
PurCell.aggregate.text = priceS;
}
return PurCell;
}
#pragma tableView的点击事件 进行到下一个界面的时候
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
static NSString *cellIdentifiter = @"WifiCellIdentifiter";
PurchaseView *wifiCell= [tableView dequeueReusableCellWithIdentifier:cellIdentifiter];
//无色
wifiCell.selectionStyle = UITableViewCellSelectionStyleNone;
if (wifiCell == nil) {
wifiCell = [[PurchaseView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifiter];
}
NSUInteger row = [indexPath row];
if(row<self.dataList.count){
Signals *signals = [[Signals alloc] init];
signals = [self.dataList objectAtIndex:row];
PseDetailsController *wdView = [[PseDetailsController alloc] init];
wdView.title = signals.pono;
// wdView.currentIndex = (int)row;
// wdView.salNumber = signals.serialnumber;//设备地址
[self.navigationController pushViewController:wdView animated:YES];
}
}
@end
5.PurchaseModel.h(服务器的请求)
#import <UIKit/UIKit.h>
#import "AFNetworking.h"
#import "Signals.h"
#import "MJExtension.h"
@protocol PurModelDelegate <NSObject>
//成功的时候
-(void)getDataSuccess:(NSArray *) list;
//失败的时候
-(void)getDataFail:(NSString *) message;
@end
@interface PurchaseModel : NSObject
@property(nonatomic,assign) id<PurModelDelegate> delegate;
//获取网络数据
-(void)getWifiData;
@end
6.PurchaseModel.h.m
#import "PurchaseModel.h"
@implementation PurchaseModel
//获取到网络数据
-(void)getWifiData{
NSDictionary *parameters = @{@"page":@"1",//参数
@"pagesize":@"10"//参数
};
//请求的url
NSString *urlString = @"你自己的服务器请求url";
//请求的managers
AFHTTPSessionManager *managers = [AFHTTPSessionManager manager];
managers.requestSerializer=[AFJSONRequestSerializer serializer];
//managers.responseSerializer=[AFJSONResponseSerializer serializer];
managers.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain",@"application/json",@"text/javascript", nil];
//如果不需要参数,parameters填写为:nil
[managers POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"请求成功,服务器返回的信息%@",responseObject[@"data"]);
NSMutableArray *array = [NSMutableArray array];
//NSArray *keys = [responseObject[@"data"] key];
for (int i = 0; i < [responseObject[@"data"] count]; ++i){
NSDictionary *key = [responseObject[@"data"] objectAtIndex: i];
Signals *signal = [Signals mj_objectWithKeyValues:key];
// signal.serialnumber = keyName;
[array addObject:signal];
if(array.count>0){
if([self.delegate respondsToSelector:@selector(getDataSuccess:)]){
[self.delegate getDataSuccess:array];
}
}else{
if([self.delegate respondsToSelector:@selector(getDataFail:)]){
[self.delegate getDataFail:@"数据获取错误"];
}
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败,服务器返回的错误信息%@",error);
}];
}
//发送广播数据信息
-(void)sendNotificationData:(NSMutableArray *)array{
if(array>0){
NSDictionary *wifiData = [NSDictionary dictionaryWithObject:array forKey:@"wifiData"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"wifiNofiction" object:nil userInfo:wifiData];
}
}
@end
7.Signals.h(对应的模型字典,也就是上面请求出来的Json数据,把需要用到的写进去)
#import <Foundation/Foundation.h>
//#import "MJExtension.h"
@interface Signals : NSObject
@property(nonatomic,strong) NSString *addDate;
@property(nonatomic,strong) NSString *currencyName;
@property(nonatomic,strong) NSString *pono;
@property(nonatomic,strong) NSString *priceS;
@property(nonatomic,strong) NSString *shdate;
@property(nonatomic,strong) NSString *shname;
@property(nonatomic,strong) NSString *spdate;
@property(nonatomic,strong) NSString *spname;
@property(nonatomic,strong) NSString *supplier_NO;
@property(nonatomic,strong) NSString *supplier_Name;
@end
8.Signals.m
#import "Signals.h"
@implementation Signals
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
@end
重点的导入文件:
1.#import "MJExtension.h"(JSON转字典等,第三方框架);
2.#import "AFNetworking.h"(请求网络数据框架);
基本实现代码都在以上,获取服务器JSON数据并动态显示到UITableView列表,如果有不懂的可以提出来,若对您有所帮助,请点个赞,还会继续发表更炫酷的文章,转载请标注https://mp.csdn.net/mdeditor。
最终效果图: