IOS-MVC层读取服务器接口JSON数据
此篇文章主要讲述获取服务器JSON接口数据,以便大家在今后的物联网信息时代,移动数据肯定都是需要网络数据的,那么就需要用一个分布集中,整体化的,规范性的创建所需的文件,同时方便以后维护;
分别为:M(model),M(manager),V(view),C(cell),C(controller);
具体程序如下:
一:YSMasonryManager.h
#import#import"BaseManager.h" #import"YSMasonryModel.h" @protocolYSMasonryManagerDelegate -(void)networkSuccess:(YSMasonryModel*_Nullable)result; -(void)networkFail:(NSString*_Nullable)result; @end NS_ASSUME_NONNULL_BEGIN @interfaceYSMasonryManager:BaseManager @property(weak,nonatomic)id delegate; -(void)getDeviceProile:(NSString*)limitOffset:(NSString*)offset; @end NS_ASSUME_NONNULL_END
二:YSMasonryManager.m
#import"YSMasonryManager.h" @implementationYSMasonryManager -(void)getDeviceProile:(NSString*)limitOffset:(NSString*)offset{ NSString*strUrl=[NSStringstringWithFormat:@"%@api/internal/profile",DEVICE_BASE_URL]; //JSON [PPNetworkHelpersetRequestSerializer:PPRequestSerializerHTTP]; [PPNetworkHelpersetResponseSerializer:PPResponseSerializerJSON]; //配置Jwt文件 [PPNetworkHelpersetValue:USERJWTKEYSforHTTPHeaderField:@"Grpc-Metadata-Authorization"]; [PPNetworkHelperGET:strUrlparameters:@""success:^(idresponseObject){ YSMasonryModel*net=[YSMasonryModelmj_objectWithKeyValues:responseObject]; if(net.organizations.count>0){ if([self.delegaterespondsToSelector:@selector(networkSuccess:)]){ [self.delegatenetworkSuccess:net]; } }else{ if([self.delegaterespondsToSelector:@selector(networkFail:)]){ [self.delegatenetworkFail:@"GetFail!"]; } } }failure:^(NSError*error){ //NSError*newError=[NSErrorreturnErrorWithError:error]; if([self.delegaterespondsToSelector:@selector(networkFail:)]){ [self.delegatenetworkFail:@"cc"]; } }]; } @end
分析:
#import"BaseManager.h"//头部manager对象 #import"YSMasonryModel.h"//模型层
三:YSMasonryModel.h
#import#import"BaseModel.h" #import"YSMasonryPileModel.h" NS_ASSUME_NONNULL_BEGIN @interfaceYSMasonryModel:BaseModel @property(nonatomic,copy)NSString*settings; @property(nonatomic,copy)NSArray*organizations; @property(nonatomic,copy)NSString*user; +(NSDictionary*)mj_objectClassInArray; @end NS_ASSUME_NONNULL_END
四:YSMasonryModel.m
#import"YSMasonryModel.h" @implementationYSMasonryModel +(NSDictionary*)mj_objectClassInArray{ return@{@"organizations":[YSMasonryPileModelclass],}; } @end
五:YSMasonryPileModel.h
#import#import"BaseModel.h" NS_ASSUME_NONNULL_BEGIN @interfaceYSMasonryPileModel:BaseModel @property(nonatomic,assign)NSString*isAdmin; @property(nonatomic,copy)NSString*organizationID; @property(nonatomic,copy)NSString*organizationName; @property(nonatomic,copy)NSString*createdAt; @property(nonatomic,copy)NSString*updatedAt; @property(nonatomic,assign)NSString*disableAssignExistingUsers; @property(nonatomic,copy)NSString*email; @property(nonatomic,copy)NSString*uid; @property(nonatomic,assign)NSString*isActive; @property(nonatomic,copy)NSString*note; @property(nonatomic,assign)NSString*sessionTTL; @property(nonatomic,copy)NSString*username; -(id)initWithDict:(NSDictionary*)dict; @end NS_ASSUME_NONNULL_END
六:YSMasonryPileModel.m
#import"YSMasonryPileModel.h" @implementationYSMasonryPileModel +(NSDictionary*)mj_replacedKeyFromPropertyName { return@{@"uid":@"uid"}; } -(id)initWithDict:(NSDictionary*)dict{ if(self=[superinit]){ self.createdAt=dict[@"createdAt"]; //@"gatewayDiscoveryEnabled":@(enable), self.isAdmin=dict[@"isAdmin"]; self.organizationID=dict[@"organizationID"]; self.organizationName=dict[@"networkServerID"]; self.updatedAt=dict[@"updatedAt"]; self.disableAssignExistingUsers=dict[@"disableAssignExistingUsers"]; self.email=dict[@"email"]; self.uid=dict[@"id"]; self.isActive=dict[@"isActive"]; self.note=dict[@"note"]; self.sessionTTL=dict[@"sessionTTL"]; self.username=dict[@"username"]; } returnself; } @end
七:YSMasonryView.h
#import#import"BaseView.h" NS_ASSUME_NONNULL_BEGIN @interfaceYSMasonryView:BaseView @property(nonatomic,strong)UITableView*mDevericePile; @end NS_ASSUME_NONNULL_END
八:YSMasonryView.m
#import#import"YSMasonryView.h" #ifdef__OBJC__ //definethisconstantifyouwanttouseMasonrywithoutthe'mas_'prefix #defineMAS_SHORTHAND //definethisconstantifyouwanttoenableauto-boxingfordefaultsyntax #defineMAS_SHORTHAND_GLOBALS #import"Masonry.h" #endif @implementationYSMasonryView -(void)initView{ _mDevericePile=[[UITableViewalloc]init]; _mDevericePile.separatorStyle=UITableViewCellSeparatorStyleSingleLine; [selfaddSubview:_mDevericePile]; [_mDevericePilemakeConstraints:^(MASConstraintMaker*make){ make.top.equalTo(self).offset(0); make.left.equalTo(self).offset(0); make.right.equalTo(self).offset(0); make.bottom.equalTo(self).offset(0); }]; } @end
九:YSMasonryCell.h
#import#import"BaseCell.h" NS_ASSUME_NONNULL_BEGIN @interfaceYSMasonryCell:BaseCell @property(nonatomic,strong)UIImageView*mNetImgVw; @property(nonatomic,strong)UILabel*mNetNameLb; @property(nonatomic,strong)UILabel*mNetServerLb; @property(nonatomic,strong)UILabel*mNetTimeLb; @end NS_ASSUME_NONNULL_END
十:YSMasonryCell.m
#import"YSMasonryCell.h" @implementationYSMasonryCell -(void)awakeFromNib{ [superawakeFromNib]; } -(instancetype)initWithStyle:(UITableViewCellStyle)stylereuseIdentifier:(NSString*)reuseIdentifier{ self=[superinitWithStyle:stylereuseIdentifier:reuseIdentifier]; if(self){ UIView*mainView=[[UIViewalloc]init]; mainView.layer.cornerRadius=8; mainView.layer.borderColor=[[UIColorgrayColor]CGColor]; mainView.layer.borderWidth=1; [selfaddSubview:mainView]; [mainViewmakeConstraints:^(MASConstraintMaker*make){ make.left.equalTo(self).offset(10); make.right.equalTo(self).offset(-10); make.top.equalTo(self).offset(10); make.bottom.equalTo(self).offset(-10); }]; _mNetImgVw=[[UIImageViewalloc]init]; [mainViewaddSubview:_mNetImgVw]; [_mNetImgVwmakeConstraints:^(MASConstraintMaker*make){ make.centerY.equalTo(self); make.left.equalTo(self).offset(20); make.width.equalTo(@25); make.height.equalTo(@25); }]; //Net名称 _mNetNameLb=[[UILabelalloc]init]; _mNetNameLb.textColor=[UIColorgrayColor]; _mNetNameLb.font=[UIFontfontWithName:@"Helvetica-Bold"size:16]; _mNetNameLb.textAlignment=NSTextAlignmentLeft; [mainViewaddSubview:_mNetNameLb]; [_mNetNameLbmakeConstraints:^(MASConstraintMaker*make){ make.top.equalTo(mainView).offset(5); make.left.equalTo(self.mNetImgVw).offset(35); make.right.equalTo(mainView).offset(-5); make.height.equalTo(@30); }]; //创建时间 _mNetTimeLb=[[UILabelalloc]init]; _mNetTimeLb.textColor=[UIColorgrayColor]; _mNetTimeLb.font=[UIFontfontWithName:@"Helvetica-Bold"size:14]; _mNetTimeLb.textAlignment=NSTextAlignmentRight; [mainViewaddSubview:_mNetTimeLb]; [_mNetTimeLbmakeConstraints:^(MASConstraintMaker*make){ make.top.equalTo(mainView).offset(10); make.right.equalTo(mainView).offset(-10); make.width.equalTo(@160); make.height.equalTo(@30); }]; //端口号 _mNetServerLb=[[UILabelalloc]init]; _mNetServerLb.textColor=[UIColorgrayColor]; _mNetServerLb.font=[UIFontfontWithName:@"Helvetica-Bold"size:16]; _mNetServerLb.textAlignment=NSTextAlignmentLeft; [mainViewaddSubview:_mNetServerLb]; [_mNetServerLbmakeConstraints:^(MASConstraintMaker*make){ make.bottom.equalTo(self).offset(-15); make.left.equalTo(self.mNetImgVw).offset(35); make.right.equalTo(mainView).offset(-10); make.height.equalTo(@30); }]; } returnself; } -(void)setSelected:(BOOL)selectedanimated:(BOOL)animated{ [supersetSelected:selectedanimated:animated]; } @end
十一:YSMasonryContller.h
#import#import"BaseViewController.h" #import"YSMasonryView.h" #import"YSMasonryCell.h" #import"YSMasonryManager.h" #import"YSMasonryPileModel.h" #import"MBProgressHUD.h" #import"MJRefresh.h" #import"WHToast.h" NS_ASSUME_NONNULL_BEGIN @interfaceYSMasonryContller:BaseViewController @property(nonatomic,strong)YSMasonryView*lgdView; @property(nonatomic,strong)YSMasonryManager*lgdManager; @property(strong,nonatomic)NSMutableArray*dataList; @property(strong,nonatomic)MBProgressHUD*hud; @property(nonatomic,strong)YSMasonryPileModel*model; @property(nonatomic,strong)NSString*organizations; @property(assign,nonatomic)intlimit; @property(assign,nonatomic)intoffsert; @end NS_ASSUME_NONNULL_END
十二:YSMasonryContller.m
#import#import"YSMasonryContller.h" #defineCELLIDENTIFITER"NETTABLEVIEWCELL" @interfaceYSMasonryContller() @end @implementationYSMasonryContller -(void)viewDidLoad{ [superviewDidLoad]; [selfinitData]; } //头部标题a -(void)customContentView{ UIColor*commonBlue=[self.commonUtilstringToColor:@"#333333"]; [self.navigationController.navigationBarsetBarTintColor:commonBlue]; self.navigationController.navigationBar.tintColor=[UIColorwhiteColor]; self.navigationItem.title=@"NetWorkServer"; } -(void)customNavigationLeftItem{ UIBarButtonItem*item=[[UIBarButtonItemalloc]initWithTitle:@"Back"style:UIBarButtonItemStylePlaintarget:nilaction:nil]; self.navigationItem.backBarButtonItem=item; } -(void)customNavigationRightItem{ UIBarButtonItem*add=[[UIBarButtonItemalloc]initWithTitle:@"Add"style:UIBarButtonItemStylePlaintarget:selfaction:@selector(onAddClick)]; add.tintColor=[UIColorwhiteColor]; self.navigationItem.rightBarButtonItem=add; } -(void)initData{ UIView*view=[[UIViewalloc]init]; self.lgdView.mDevericePile.tableFooterView=view; self.lgdView.frame=self.view.bounds; [self.viewaddSubview:self.lgdView]; _limit=5; _offsert=0; } //启动时的运行数据 -(void)viewDidAppear:(BOOL)animated{ [superviewDidAppear:animated]; //加载数据 NSString*slimit=[NSStringstringWithFormat:@"%d",_limit]; NSString*soffset=[NSStringstringWithFormat:@"%d",_offsert]; [self.lgdManagergetDeviceProile:slimitOffset:soffset]; } -(YSMasonryView*)lgdView{ if(_lgdView==nil){ _lgdView=[[YSMasonryViewalloc]init]; _lgdView.mDevericePile.dataSource=(id)self; _lgdView.mDevericePile.delegate=(id)self; } return_lgdView; } -(YSMasonryManager*)lgdManager{ if(_lgdManager==nil){ _lgdManager=[[YSMasonryManageralloc]init]; _lgdManager.delegate=(id)self; } return_lgdManager; } -(NSMutableArray*)dataList{ if(_dataList==nil){ _dataList=[NSMutableArrayarray]; } return_dataList; } #pragmamarkgetnetworkdata -(void)networkSuccess:(YSMasonryModel*_Nullable)result{ [self.lgdView.mDevericePile.mj_headerendRefreshing]; [self.lgdView.mDevericePile.mj_footerendRefreshing]; self.dataList=[NSMutableArrayarrayWithArray:result.organizations]; [self.lgdView.mDevericePilereloadData]; } -(void)networkFail:(NSString*_Nullable)result{ [self.lgdView.mDevericePile.mj_headerendRefreshing]; [self.lgdView.mDevericePile.mj_footerendRefreshing]; [WHToastshowMessage:resultoriginY:500duration:2finishHandler:^{ }]; } #pragmamarktableView -(NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section{ returnself.dataList.count; } -(UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath{ YSMasonryCell*cell=[tableViewdequeueReusableCellWithIdentifier:@CELLIDENTIFITER]; if(cell==nil){ cell=[[YSMasonryCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:@CELLIDENTIFITER]; } if(_dataList.count>0){ YSMasonryPileModel*model=[[YSMasonryPileModelalloc]initWithDict:[self.dataListobjectAtIndex:indexPath.row]]; if(model!=nil){ //cell.mNetImgVw.image=[UIImageimageNamed:@"net"]; //cell.mNetNameLb.text=model.isAdmin; //cell.mNetTimeLb.text=[selfdateAndStrings:model.createdAt]; cell.mNetServerLb.text=@"vv"; } } returncell; } -(void)tableView:(UITableView*)tableViewdidSelectRowAtIndexPath:(NSIndexPath*)indexPath { if(_dataList.count>0){ YSMasonryPileModel*model=[[YSMasonryPileModelalloc]initWithDict:[self.dataListobjectAtIndex:indexPath.row]]; if(model!=nil){ //[selfupdateNetWorkServer:model.deviceprolieid]; } } } -(CGFloat)tableView:(UITableView*)tableViewheightForRowAtIndexPath:(NSIndexPath*)indexPath { return100; } -(NSString*)dateAndStrings:(NSString*)date{ if(date!=nil){ NSArray*strtime=[datecomponentsSeparatedByString:@"T"]; //NSString*strtime=[datestringByReplacingOccurrencesOfString:@"T"withString:@""]; returnstrtime[0]; } return@"None"; } //添加add设备 -(void)onAddClick{ } @end
十三:所用到的常量一些定义:
Constants.h
#import#defineBASE_URL@"http://110.22.33/ilLoRaWan/" #defineUSERJWTKEYS@"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJsb3JhLWFwcC1zZXJ2ZXIiLCJhdWQiOiJsb3JhLWFwc"
至此!
以上详细的代码,主要就是mode数据层那,修改自己的json的返回数据,与一些字典类型的转换,就没其他的难点了。这样写的主要目的是,思路逻辑更清晰,后期维护也简单,分开着写代码更简洁。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。