以上一篇Google IOT Core之 Cloud Function 部署(一)阐述了如何使用Google IOT Core 以及 Cloud Function云函数为链接,在此,下面我们来了解,如何在移动端获取到Google IOT Core 设备/注册表。你所需要的信息,只要Google IOT Core有API,就可以函数实现。
1.部署了完成好的云函数功能,访问云函数URL。
2.如何编写IOS APP。
3.客户的需求是什么?我们要怎么去实现?
4.利用POST,GET等方式,去调用Google IOT Core API。
5.获取到JSON,进行解析。
一:Postman测试Google Iot Core设备得到JSON接口数据;
二:IOS项目结构设计:
1.HomeView.h
#import
#import "BaseView.h"
@protocol HomeViewDelegate
-(void)onClick;
@end
NS_ASSUME_NONNULL_BEGIN
@interface HomeView : BaseView
@property(weak,nonatomic) id delegate;
@property(nonatomic, strong) UITableView *tableView;
@end
NS_ASSUME_NONNULL_END
2.HomeView.m
#import "HomeView.h"
@implementation HomeView
-(instancetype) init{
self = [super init];
if(self){
[self initView];
}
return self;
}
-(void)initView{
_tableView = [[UITableView alloc] init];
_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[self addSubview:_tableView];
[_tableView makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self).offset(70);
make.left.equalTo(self).offset(0);
make.right.equalTo(self).offset(0);
make.bottom.equalTo(self).offset(-60);
}];
UIView *bottomView = [[UIView alloc] init];
bottomView.backgroundColor = [self.cmUtil stringToColor:@"#c1c1c1"];
[self addSubview:bottomView];
[bottomView makeConstraints:^(MASConstraintMaker *make){
make.left.equalTo(self).offset(0);
make.right.equalTo(self).offset(0);
make.bottom.equalTo(self).offset(0);
make.height.equalTo(@60);
}];
UIImageView *addDeviceLb = [[UIImageView alloc] init];
addDeviceLb = [[UIImageView alloc] init];
addDeviceLb.image=[UIImage imageNamed:@"add"];
[bottomView addSubview:addDeviceLb];
[addDeviceLb makeConstraints:^(MASConstraintMaker *make){
make.centerX.mas_equalTo(0);
make.centerY.mas_equalTo(0);
make.width.equalTo(@39);
make.height.equalTo(@39);
}];
UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClick)];
[bottomView addGestureRecognizer:tapGesturRecognizer];
}
-(void)onClick{
if(self.delegate){
[self.delegate onClick];
}
}
@end
3.cell.h模块层tabview属性的定义;
#import
#import "BaseViewCell.h"
#import "CommonUtil.h"
NS_ASSUME_NONNULL_BEGIN
@interface HomeViewCell : BaseViewCell
@property(nonatomic,strong) UIView *topView;
@property(nonatomic,strong) UIView *conView;
@property(nonatomic,strong) UIView *mMainVw;
@property(nonatomic, strong) UIView *btmView;
@property (strong, nonatomic) UILabel *mDeviceNameLb;
@property (strong, nonatomic) UILabel *mDeviceRssiLb;
@property (strong, nonatomic) UILabel *mDeviceAddreLb;
@property (strong, nonatomic) UILabel *mConentMqtt;
@property(nonatomic,strong) UIImageView *mStatusIv;
@property(nonatomic,strong) UIImageView *mDeviceStatus;
@property(nonatomic,strong) UIImageView *mBatteryStatus;
@property(nonatomic,strong) UIImageView *mFanStatus;
@end
NS_ASSUME_NONNULL_END
4.cell.m
#import "HomeViewCell.h"
@implementation HomeViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if(self){
CommonUtil *cmUtil = [[CommonUtil alloc] init];
// 第一段布局
// 高度 100
// _topView = [[UIView alloc] init];
// _topView.backgroundColor = [cmUtil stringToColor:@"#EAEAEA"];
// _topView.layer.cornerRadius = 5.f;
// _topView.clipsToBounds=YES;
// _topView.layer.shadowColor=[UIColor blackColor].CGColor;
// _topView.layer.shadowOffset=CGSizeMake(5, 5);
// _topView.layer.shadowOpacity=0.5;
// _topView.layer.shadowRadius=5;
// [self addSubview:_topView];
//
// [_topView makeConstraints:^(MASConstraintMaker *make){
// make.left.equalTo(self).offset(5);
// make.right.equalTo(self).offset(-5);
// make.top.equalTo(self).offset(0);
// make.height.equalTo(100);
// }];
//
// UILabel *addDeviceLb = [[UILabel alloc] init];
// addDeviceLb.textColor = [UIColor blackColor];
// addDeviceLb.font = [UIFont fontWithName:@"Helvetica-Bold" size:23];
// addDeviceLb.textAlignment = NSTextAlignmentCenter;
// [_topView addSubview:addDeviceLb];
//
// [addDeviceLb makeConstraints:^(MASConstraintMaker *make){
// make.centerX.equalTo(self.topView);
// make.centerY.equalTo(self.topView);
// make.width.equalTo(@200);
// make.height.equalTo(@30);
// }];
//
// addDeviceLb.text = @"Add Device";
//第二段布局
self.mMainVw = [[UIView alloc] init];
self.mMainVw.backgroundColor = [cmUtil stringToColor:@"#EAEAEA"];
self.mMainVw.layer.cornerRadius = 5.f;
self.mMainVw.clipsToBounds=YES;
self.mMainVw.layer.shadowColor=[UIColor blackColor].CGColor;
self.mMainVw.layer.shadowOffset=CGSizeMake(5, 5);
self.mMainVw.layer.shadowOpacity=0.5;
self.mMainVw.layer.shadowRadius=5;
[self addSubview:self.mMainVw];
[self.mMainVw makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self).offset(10);
make.left.equalTo(self).offset(10);
make.right.equalTo(self).offset(-10);
make.bottom.equalTo(self).offset(-10);
}];
self.mStatusIv = [[UIImageView alloc] init];
[self.mMainVw addSubview:self.mStatusIv];
[self.mStatusIv makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self.mMainVw).offset(15);
make.left.equalTo(self.mMainVw).offset(10);
make.width.equalTo(@15);
make.height.equalTo(@15);
}];
self.mDeviceStatus = [[UIImageView alloc] init];
[self.mStatusIv addSubview:self.mDeviceStatus];
[self.mDeviceStatus makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self.mStatusIv).offset(0);
make.left.equalTo(self.mStatusIv).offset(20);
make.width.equalTo(@15);
make.height.equalTo(@15);
}];
self.mBatteryStatus = [[UIImageView alloc] init];
[self.mDeviceStatus addSubview:self.mBatteryStatus];
[self.mBatteryStatus makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self.mDeviceStatus).offset(0);
make.left.equalTo(self.mDeviceStatus).offset(20);
make.width.equalTo(@15);
make.height.equalTo(@15);
}];
self.mFanStatus = [[UIImageView alloc] init];
[self.mBatteryStatus addSubview:self.mFanStatus];
[self.mFanStatus makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self.mBatteryStatus).offset(0);
make.left.equalTo(self.mBatteryStatus).offset(20);
make.width.equalTo(@15);
make.height.equalTo(@15);
}];
self.mDeviceNameLb = [[UILabel alloc] init];
self.mDeviceNameLb.textColor = [UIColor blackColor];
self.mDeviceNameLb.font = [UIFont fontWithName:@"Helvetica-Bold" size:23];
self.mDeviceNameLb.textAlignment = NSTextAlignmentCenter;
[self.mMainVw addSubview:self.mDeviceNameLb];
[self.mDeviceNameLb makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self.mMainVw).offset(30);
make.left.equalTo(self.mMainVw).offset(0);
make.right.equalTo(self.mMainVw).offset(-10);
make.height.equalTo(@30);
}];
self.mConentMqtt = [[UILabel alloc] init];
self.mConentMqtt.textColor = [UIColor blackColor];
self.mConentMqtt.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];
self.mConentMqtt.textAlignment = NSTextAlignmentCenter;
[self.mMainVw addSubview:self.mConentMqtt];
[self.mConentMqtt makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self.mDeviceNameLb).offset(10);
make.left.equalTo(self.mMainVw).offset(135);
make.right.equalTo(self.mMainVw).offset(0);
make.height.equalTo(@30);
}];
self.mDeviceAddreLb = [[UILabel alloc] init];
self.mDeviceAddreLb.textColor = [UIColor grayColor];
self.mDeviceAddreLb.font = [UIFont fontWithName:@"Helvetica" size:15];
self.mDeviceAddreLb.textAlignment = NSTextAlignmentCenter;
[self.mMainVw addSubview:self.mDeviceAddreLb];
[self.mDeviceAddreLb makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self.mDeviceNameLb).offset(40);
make.left.equalTo(self.mMainVw).offset(0);
make.right.equalTo(self.mMainVw).offset(-10);
make.height.equalTo(@30);
}];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
5.HomeManager.h(接口的定义)
#import
#import "BaseManager.h"
#import "NSError+YJPError.h"
#import "Constants.h"
#import "PPNetworkHelper.h"
#import "DeviceModel.h"
@protocol HomeManagerDelegate
//Get All Devices
- (void)getDevices:(NSArray*_Nullable) resultes;
- (void)getDevicesFail:(NSString*_Nullable) result;
@end
NS_ASSUME_NONNULL_BEGIN
@interface HomeManager : BaseManager
@property(weak,nonatomic) id delegate;
/**
Get All Devices
*/
-(void)getDevices;
@end
NS_ASSUME_NONNULL_END
6.HomeManager.m
#import "HomeManager.h"
@implementation HomeManager
/**
Get All Devices
*/
-(void)getDevices{
NSString *strUrl = [NSString stringWithFormat:@"%@devices",@“www.baidu.com/device”];
NSDictionary *params = @{
@"args":@"get_devices",
@"registryId":BASE_REGISTRY,
@"cloudRegion":BASE_CREGION,
};
//HTTP+JSON
[PPNetworkHelper setRequestSerializer:PPRequestSerializerHTTP];
[PPNetworkHelper setResponseSerializer:PPResponseSerializerJSON];
[PPNetworkHelper GET:strUrl parameters:params success:^(id responseObject){
DeviceModel *model = [DeviceModel mj_objectWithKeyValues:responseObject];
if(model.data.count>0){
if([self.delegate respondsToSelector:@selector(getDevices:)]){
[self.delegate getDevices:model.data];
}
}else{
if([self.delegate respondsToSelector:@selector(getDevicesFail:)]){
[self.delegate getDevicesFail:@"Get Devices Fail!"];
}
}
} failure:^(NSError *error){
NSLog(@"erro----+%@",error);
NSError *newError = [NSError returnErrorWithError:error];
if([self.delegate respondsToSelector:@selector(getDevicesFail:)]){
[self.delegate getDevicesFail:newError.localizedDescription];
}
}];
}
@end
7.HomeViewController.h
#import
#import "BaseViewController.h"
#import "MeViewController.h"
#import "HomeView.h"
#import "HomeViewCell.h"
#import "HomeManager.h"
#import "BTAlertController.h"
#import "AddDeviceView.h"
#import "CommonDefaults.h"
NS_ASSUME_NONNULL_BEGIN
@interface HomeViewController : BaseViewController
@end
NS_ASSUME_NONNULL_END
8.HomeViewController.m
#import "HomeViewController.h"
#import "BleViewController.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "WHToast.h"
#define CELLIDENTIFITER "HOMETABLEVIEWCELL"
@interface HomeViewController (){
MBProgressHUD *hud;
}
@property(nonatomic,strong) HomeView *homeView;
@property(nonatomic,strong) HomeManager *homeManager;
@property(nonatomic,strong) AddDeviceView *addDevice;
@property(strong, nonatomic) NSMutableArray *deviceList;
@end
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
/*
程序加载的时候调用
*/
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
if(_deviceList.count>0){
//重新加载数据
[_deviceList removeAllObjects];
}
[self showHud];
//program run get devices
[self.homeManager getDevices];
}
-(void)customContentView{
UIColor *commonBlue = [self.cmUtil stringToColor:@"#333333"];
[self.navigationController.navigationBar setBarTintColor:commonBlue];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
self.navigationItem.title = @"Reading";
}
-(void)customNavigationRightItem{
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"me"] style:UIBarButtonItemStylePlain target:self action:@selector(onMeClick)];
item.tintColor = [UIColor whiteColor];
self.navigationItem.rightBarButtonItem = item;
}
- (void)customNavigationLeftItem{
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"blue"] style:UIBarButtonItemStylePlain target:self action:@selector(onAddClick)];
item.tintColor = [UIColor whiteColor];
self.navigationItem.leftBarButtonItem = item;
}
/*
display loading...
*/
-(void)showHud{
hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
hud.bezelView.color = [[UIColor blackColor] colorWithAlphaComponent:0.7];
hud.label.text = NSLocalizedString(@"Data Loading...", @"HUD loading title");
hud.contentColor = [UIColor whiteColor];
//正常情况下是20秒后消失
[hud hideAnimated:YES afterDelay:20.0f];
}
/**
hide loading...
*/
-(void)hideHud{
[hud hideAnimated:YES afterDelay:0.5f];
}
-(void)initData{
UIView *view = [[UIView alloc] init];
self.homeView.tableView.tableFooterView = view;
self.homeView.frame = self.view.bounds;
[self.view addSubview:self.homeView];
[self setUpRefresh];
}
- (void)setUpRefresh{
__weak __typeof(self) weakSelf = self;
self.homeView.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
[weakSelf loadRefData];
}];
//self.homeView.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}
-(void)loadRefData{
if(self.deviceList.count>0){
[self.deviceList removeAllObjects];
}
//[self.homeView.tableView reloadData];
[self.homeManager getDevices];
}
-(void)loadMoreData{
[self loadRefData];
}
-(void) onMeClick{
MeViewController * me = [[MeViewController alloc]init];
me.title = @"Me";
[self.navigationController pushViewController:me animated:YES];
}
-(HomeView*)homeView{
if(!_homeView){
_homeView = [[HomeView alloc] init];
_homeView.tableView.delegate = (id)self;
_homeView.tableView.dataSource = (id)self;
_homeView.delegate = (id)self;
}
return _homeView;
}
-(void) onAddClick{
BleViewController *ble = [[BleViewController alloc] init];
[self.navigationController pushViewController:ble animated:YES];
}
-(HomeManager*)homeManager{
if(_homeManager==nil){
_homeManager = [[HomeManager alloc] init];
_homeManager.delegate = (id)self;
}
return _homeManager;
}
-(NSMutableArray*)deviceList{
if(!_deviceList){
_deviceList = [[NSMutableArray alloc] init];
}
return _deviceList;
}
//点击按钮添加设备
-(void)homeAddDevice{
_addDevice = [[AddDeviceView alloc] init];
_addDevice.commonTf.delegate = self;
__weak __typeof(self) weakSelf = self;
_addDevice.commonTf.text = @"xxxx";
//确定的时候
[_addDevice setSureBolck:^(BOOL clickStatu) {
NSString *name = weakSelf.addDevice.commonTf.text;
//执行发送数据
if(![name isEqualToString:@""]&&name!=nil){
[weakSelf showHud];
[weakSelf.homeManager addDevice:name];
}else{
[WHToast showMessage:@"Input not empty" originY:500 duration:2 finishHandler:^{
}];
}
}];
}
#pragma mark HomeViewDelegate
-(void)onClick{
[self homeAddDevice];
}
#pragma mark HomeManagerDelegate
//Get All Devices
- (void)getDevices:(NSArray*_Nullable) resultes{
[self.homeView.tableView.mj_header endRefreshing];
[self hideHud];
if(resultes.count>0){
self.deviceList = [NSMutableArray arrayWithArray:resultes];
[self.homeView.tableView reloadData];
}
}
- (void)getDevicesFail:(NSString*_Nullable) result{
[self.homeView.tableView.mj_header endRefreshing];
[self hideHud];
[WHToast showMessage:result originY:500 duration:2 finishHandler:^{
}];
}
//Add Device
-(void)addDevice:(DeviceModel* _Nullable) result{
//[self.homeView.tableView.mj_header endRefreshing];
[self hideHud];
//如果添加成功
if(result!=nil){
NSString *allkey = [NSString stringWithFormat:@"%@%@",PRIVATE_KEY,result.deviceId];
//存储privteKey
[[CommonDefaults shared] saveValue:result.privateKey forKey:allkey];
//开启
[self showHud];
//绑定设备
[self.homeManager bindDeviceMqtt:result.deviceId privateKey:result.privateKey];
}
}
-(void)addDeviceFail:(NSString *_Nullable) result{
[self hideHud];
[WHToast showMessage:result originY:500 duration:2 finishHandler:^{
}];
}
#pragma mark UITableView
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 130;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _deviceList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
HomeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@CELLIDENTIFITER];
if (cell == nil) {
cell = [[HomeViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@CELLIDENTIFITER];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
if([_deviceList count]>0){
Device *model = [_deviceList objectAtIndex:indexPath.row];
cell.mDeviceNameLb.text = model.deviceId;
cell.mStatusIv.image=[UIImage imageNamed:@"nonet"];
cell.mDeviceStatus.image=[UIImage imageNamed:@"device_nonet"];
cell.mBatteryStatus.image=[UIImage imageNamed:@"battery"];
cell.mFanStatus.image=[UIImage imageNamed:@"fan"];
cell.mDeviceAddreLb.text = model.numId;
//信号值 需要去修改
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
HomeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@CELLIDENTIFITER];
if (cell == nil) {
cell = [[HomeViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@CELLIDENTIFITER];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
}
//用完之后需要关闭掉
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
}
#pragma mark KeyBoard
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[self.addDevice.commonTf resignFirstResponder];
return YES;
}
//点击空白处让键盘隐藏起来
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.addDevice.commonTf resignFirstResponder];
}
@end
三:最终效果图IOS实现: