使用AWS-AppSync实时监控物联网设备iOS端
创始人
2024-03-12 16:24:53
0

aws-appsync-iot-core-实时iOS端示例

第一步参考如下资料

  1. 第一步找资料

网址: https://aws.amazon.com/cn/blogs/mobile/iot-with-aws-appsync/

iOS的sdk是 : https://github.com/aws-amplify/aws-sdk-ios

android的sdk是: https://github.com/aws-amplify/aws-sdk-android

传感器使用AWS IoT 设备 SDK连接到云中的AWS IoT Core并发布温度消息。
AWS IoT Core 接收消息并将它们转发到AWS Lambda函数。
Lambda 函数执行AWS AppSync GraphQL 突变,更新Amazon DynamoDB并将更改后的数据广播给移动应用程序订阅者。
移动应用程序接收数据并实时更新屏幕值。

如以下资料
https://docs.amplify.aws/lib-v1/graphqlapi/subscribe-data/q/platform/ios/

第二步搭建项目

准备工作
  1. 首先打开xcode创建项目 使用的是 Amplify v1 版本记住不要使用错了

项目的参数设置如下:


Product Name: input AmplifyDemoInterface: select StoryboardLanguage: Swift

点击next选择自己适合的位置

  1. iOS 项目打开选择 TARGETS->AmplifyDemo->General->Deployment Info, please select iOS 11.0

接下来要进行的是导入包操作,此步骤要等很久

打开电脑的终端 输入 cd 进入 以下是我的电脑信息

(1). 找到对应的创建文件夹进入(注意你得安装了 cocopads 安装教程: https://www.jianshu.com/p/fe4e1bf1c15d )


Last login: Fri Dec  2 09:18:50 on ttys001The default interactive shell is now zsh.
To update your account to use zsh, please run `chsh -s /bin/zsh`.
For more details, please visit https://support.apple.com/kb/HT208050.
ThermodeiMac:~ rnd$ cd /Users/Project/278161009/Github/Other/AWSServeiceTemperature/AmplifyDemo 
ThermodeiMac:AmplifyDemo rnd$ 

(2). 然后输入 pod init 进行文件夹创建


ThermodeiMac:~ rnd$ cd /Users/Project/278161009/Github/Other/AWSServeiceTemperature/AmplifyDemo 
ThermodeiMac:AmplifyDemo rnd$ pod init
ThermodeiMac:AmplifyDemo rnd$ 

(3). 进入AmplifyDemo 然后找到 Podfile文件打开输入以下的数据

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'target 'AmplifyDemo' do# Comment the next line if you don't want to use dynamic frameworksuse_frameworks!# Pods for RilCompanySensorpod 'Amplify'pod 'SnapKit', '~> 5.0.0'pod 'AWSAppSync'pod 'AWSCore'pod 'AmplifyPlugins/AWSAPIPlugin'pod 'AmplifyPlugins/AWSCognitoAuthPlugin'end

(4). 然后在控制台输入 pod install


ThermodeiMac:AmplifyDemo rnd$ pod install
Analyzing dependencies
Downloading dependencies
Installing AWSAppSync (3.6.1)
Installing AWSAuthCore (2.27.15)
Installing AWSCognitoIdentityProvider (2.27.15)
Installing AWSCognitoIdentityProviderASF (2.27.15)
Installing AWSCore (2.27.15)
Installing AWSMobileClient (2.27.15)
Installing AWSPluginsCore (1.26.2)
Installing Amplify (1.26.2)
Installing AmplifyPlugins (1.26.2)
Installing AppSyncRealTimeClient (1.10.0)
Installing ReachabilitySwift (5.0.0)
Installing SQLite.swift (0.12.2)
Installing SnapKit (5.0.1)
Installing Starscream (4.0.4)
Generating Pods project
Integrating client project[!] Please close any current Xcode sessions and use `AmplifyDemo.xcworkspace` for this project from now on.
Pod installation complete! There are 6 dependencies from the Podfile and 14 total pods installed.[!] Automatically assigning platform `iOS` with version `11.0` on target `AmplifyDemo` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.[!] Amplify has added 1 script phase. Please inspect before executing a build. See `https://guides.cocoapods.org/syntax/podspec.html#script_phases` for more information.
ThermodeiMac:AmplifyDemo rnd$ 

(5). 到此创建iOS项目部分已经结束

  1. 打开我创建的项目下载下来里面有一个utils包

(1). 找到隐藏文件 .config打开 projectName:修改成你自己的项目名称

{"projectName": "AmplifyDemo","version": "3.1","frontend": "ios","providers": ["awscloudformation"]
}

(2) 把amplify文件夹拖到创建的iOS项目中

文件结构如下:

ThermodeiMac:~ rnd$ cd /Users/Project/278161009/Github/Other/AWSServeiceTemperature/AmplifyDemo/amplify 
ThermodeiMac:amplify rnd$ 

(3) 在终端输入命令 cd … 返回上一层目录

ThermodeiMac:~ rnd$ cd /Users/Project/278161009/Github/Other/AWSServeiceTemperature/AmplifyDemo/amplify 
ThermodeiMac:amplify rnd$ cd ..
ThermodeiMac:AmplifyDemo rnd$ 

(4) 操作这一步首先你得使你的电脑安装好 具体安装请参照以下官网链接 https://docs.amplify.aws/lib-v1/project-setup/prereq/q/platform/ios/ 以下步骤是整个项目最重要的部分

1> 默认是你已经全部安装完成

2> 在终端输入 sudo amplify init 根据我的操作按照如下进行,切莫忘记步骤


ThermodeiMac:AmplifyDemo rnd$ sudo amplify init
Password:
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the environment dosandbox //切记这个必须是2-10个字母
? Choose your default editor: (Use arrow keys)
❯ Visual Studio Code Android Studio Xcode (macOS only) Atom Editor Sublime Text IntelliJ IDEA Vim (via Terminal, macOS only) 
(Move up and down to reveal more choices)? Choose your default editor: Visual Studio CodeUsing default provider  awscloudformation
? Select the authentication method you want to use: AWS profile 
❯ AWS access keys? Select the authentication method you want to use: AWS access keys
? accessKeyId:  ********************
? secretAccessKey:  ****************************************

上面这个access key怎么找到呢,打开aws服务器点击你的名称选择 安全凭证

你的安全凭证:
点击选择 -> 访问密钥(访问密钥 ID 和秘密访问密钥)
如果没有的话自己创一个点击创建新的访问密钥然后记得下载下来保存好

接下来区域的选择 由于我选择的是国外的 所以我选择了 us-east-1 你的得按照自己的选择来选择

? region:  (Use arrow keys)
❯ us-east-1 us-east-2 us-west-1 us-west-2 eu-north-1 eu-west-1 eu-west-2 
(Move up and down to reveal more choices)

(5) 整个终端操作命令如下:


Note: It is recommended to run this command from the root of your app directory
? Enter a name for the environment dosandbox
? Choose your default editor: Visual Studio Code
Using default provider  awscloudformation
? Select the authentication method you want to use: AWS access keys
? accessKeyId:  ********************
? secretAccessKey:  ****************************************
? region:  us-east-1
Adding backend environment dosandbox to AWS Amplify app: d1jvkcwlhw9pvmDeployment completed.
Deployed root stack AmplifyDemo [ ====================================amplify-amplifydemo-dosandbox… AWS::CloudFormation::Stack     CREATE_UnauthRole                     AWS::IAM::Role                 CREATE_AuthRole                       AWS::IAM::Role                 CREATE_DeploymentBucket               AWS::S3::Bucket                CREATE_Deployment bucket fetched.
⠋ Initializing your environment: dosandbox⠋ Building resource auth/sensorview74d✔ Initialized provider successfully.
✅ Initialized your environment successfully.Your project has been successfully initialized and connected to the cloud!Some next steps:
"amplify status" will show you what you've added already and if it's locally configured or deployed
"amplify add " will allow you to add features like user login or a backend API
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify console" to open the Amplify Console and view your project status
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloudPro tip:
Try "amplify add api" to create a backend API and then "amplify push" to deploy everythingThermodeiMac:AmplifyDemo rnd$ 

(6) 创建的部分已经完成然后接下来还差一步就成功了继续在终端输入 sudo amplify push

Pro tip:
Try "amplify add api" to create a backend API and then "amplify push" to deploy everythingThermodeiMac:AmplifyDemo rnd$ sudo amplify push

接下来你会看到这些请选择y


ThermodeiMac:AmplifyDemo rnd$ sudo amplify push
Password:
⠼ Fetching updates to backend environment: dosandbox from the cloud.⠋ Building r✔ Successfully pulled backend environment dosandbox from the cloud.Current Environment: dosandbox┌──────────┬────────────────────┬───────────┬───────────────────┐
│ Category │ Resource name      │ Operation │ Provider plugin   │
├──────────┼────────────────────┼───────────┼───────────────────┤
│ Auth     │ sensorview74d21f87 │ Create    │ awscloudformation │
├──────────┼────────────────────┼───────────┼───────────────────┤
│ Api      │ sensorview         │ Create    │ awscloudformation │
├──────────┼────────────────────┼───────────┼───────────────────┤
│ Function │ getsensor          │ Create    │ awscloudformation │
├──────────┼────────────────────┼───────────┼───────────────────┤
│ Function │ createsensorvalue  │ Create    │ awscloudformation │
├──────────┼────────────────────┼───────────┼───────────────────┤
│ Iotrule  │ createsensorvalue  │ Create    │ awscloudformation │
└──────────┴────────────────────┴───────────┴───────────────────┘
? Are you sure you want to continue? (Y/n) y
? Are you sure you want to continue? Yes
GraphQL schema compiled successfully.Edit your schema at /Users/Project/278161009/Github/Other/AWSServeiceTemperature/AmplifyDemo/amplify/backend/api/sensorview/schema.graphql or place .graphql files in a directory at /Users/Project/278161009/Github/Other/AWSServeiceTemperature/AmplifyDemo/amplify/backend/api/sensorview/schema
? Do you want to generate code for your newly created GraphQL API Yes
? Enter the file name pattern of graphql queries, mutations and subscriptions graphql/**/
? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscrip
tions Yes
? Enter maximum statement depth [increase from default if your schema is deeply nested] 2
? Enter the file name for the generated code ApiHelp.swift

以上的每一步不要输错 部署的如以下


Deployment completed.
Deployed root stack AmplifyDemo [ ======================================== ] 6/6amplify-amplifydemo-dosandbox… AWS::CloudFormation::Stack     UPDATE_COMPLETE                Fri Dec 02 2022 1authsensorview74d21f87         AWS::CloudFormation::Stack     CREATE_COMPLETE                Fri Dec 02 2022 1functiongetsensor              AWS::CloudFormation::Stack     CREATE_COMPLETE                Fri Dec 02 2022 1apisensorview                  AWS::CloudFormation::Stack     CREATE_COMPLETE                Fri Dec 02 2022 1functioncreatesensorvalue      AWS::CloudFormation::Stack     CREATE_COMPLETE                Fri Dec 02 2022 1iotrulecreatesensorvalue       AWS::CloudFormation::Stack     CREATE_COMPLETE                Fri Dec 02 2022 1
Deployed auth sensorview74d21f87 [ ======================================== ] 11/11SNSRole                        AWS::IAM::Role                 CREATE_COMPLETE                Fri Dec 02 2022 1UserPool                       AWS::Cognito::UserPool         CREATE_COMPLETE                Fri Dec 02 2022 1UserPoolClient                 AWS::Cognito::UserPoolClient   CREATE_COMPLETE                Fri Dec 02 2022 1UserPoolClientWeb              AWS::Cognito::UserPoolClient   CREATE_COMPLETE                Fri Dec 02 2022 1UserPoolClientRole             AWS::IAM::Role                 CREATE_COMPLETE                Fri Dec 02 2022 1UserPoolClientLambda           AWS::Lambda::Function          CREATE_COMPLETE                Fri Dec 02 2022 1UserPoolClientLambdaPolicy     AWS::IAM::Policy               CREATE_COMPLETE                Fri Dec 02 2022 1UserPoolClientLogPolicy        AWS::IAM::Policy               CREATE_COMPLETE                Fri Dec 02 2022 1UserPoolClientInputs           Custom::LambdaCallout          CREATE_COMPLETE                Fri Dec 02 2022 1IdentityPool                   AWS::Cognito::IdentityPool     CREATE_COMPLETE                Fri Dec 02 2022 1IdentityPoolRoleMap            AWS::Cognito::IdentityPoolRol… CREATE_COMPLETE                Fri Dec 02 2022 1
Deployed function getsensor [ ======================================== ] 3/3
Deployed function createsensorvalue [ ======================================== ] 4/4LambdaExecutionRole            AWS::IAM::Role                 CREATE_COMPLETE                Fri Dec 02 2022 1LambdaFunction                 AWS::Lambda::Function          CREATE_COMPLETE                Fri Dec 02 2022 1lambdaexecutionpolicy          AWS::IAM::Policy               CREATE_COMPLETE                Fri Dec 02 2022 1AmplifyResourcesPolicy         AWS::IAM::Policy               CREATE_COMPLETE                Fri Dec 02 2022 1
Deployed iotrule createsensorvalue [ ======================================== ] 2/2CreateSensorValueRule          AWS::IoT::TopicRule            CREATE_COMPLETE                Fri Dec 02 2022 1createsensorvalueallowIOTRule… AWS::Lambda::Permission        CREATE_COMPLETE                Fri Dec 02 2022 1✔ Generated GraphQL operations successfully and saved at graphql
✖ EISDIR: illegal operation on a directory, readGraphQL endpoint: https://xxxxxxxxx.appsync-api.us-east-1.amazonaws.com/graphqlGraphQL transformer version: 1ThermodeiMac:AmplifyDemo rnd$ 

(7) 全部部署完成后你账号的资源应该包含

AppSync GraphQL API
DynamoDB表
Cognito用户池
Lambda函数(2)
物联网规则

(8) 确实以上步骤完成后请在终端输入 amplify codegen models
这个生成的model将会要导出来到你的项目中


ThermodeiMac:AmplifyDemo rnd$ sudo amplify codegen models
Password:
GraphQL schema compiled successfully.Edit your schema at /Users/Project/278161009/Github/Other/AWSServeiceTemperature/AmplifyDemo/amplify/backend/api/sensorview/schema.graphql or place .graphql files in a directory at /Users/Project/278161009/Github/Other/AWSServeiceTemperature/AmplifyDemo/amplify/backend/api/sensorview/schema
Successfully generated models. Generated models can be found in /Users/Project/278161009/Github/Other/AWSServeiceTemperature/AmplifyDemo/amplify/generated/models
ThermodeiMac:AmplifyDemo rnd$ 

(9) 生成自动的swift查询代码运行 sudo amplify codegen types

ThermodeiMac:AmplifyDemo rnd$ sudo amplify codegen types
✔ Downloaded the schema
✔ Code generated successfully and saved in file ApiHelp.swift
ThermodeiMac:AmplifyDemo rnd$ 
开始部署iOS项目

目前为止你的项目配置已经全部完成接下来进入项目部分

  1. 进入AmplifyDemo 打开iOS项目 请选择 AmplifyDemo.xcworkspace

请添加图片描述

进入到项目中选择添加文件到项目 请选择“Add files to AmplifyDemo” 如下图所示 把 amplifyconfiguration 和 awsconfiguration 一起放入添加到项目中

然后再根据以上的添加方法把 amplify里面生成的generated的文件的models导入到你的项目中去
还有一个生成的 ApiHelp.swift一并导入项目

如图所示:

请添加图片描述

  1. 创建iOS的代码

此代码不重要的地方略过…

首先打开 AppDelegate.swift 导入包

import AWSAppSync
import Amplify
import AmplifyPlugins
import AWSMobileClient

然后接下添加注册

do{Amplify.Logging.logLevel = .verbosetry Amplify.add(plugin: AWSAPIPlugin(modelRegistration: AmplifyModels()))try Amplify.add(plugin: AWSCognitoAuthPlugin())try Amplify.configure()//print("Amplify configured with auth plugin")}catch{print("An error occurred setting up Amplify: \(error)")}

进一步判断是否已经登录关键代码如果登录就直接进入Home界面没有进入登录界面再去注册账号

// 判断是否登录AWSMobileClient.default().initialize{(userState, error) inif let error = error {print("error: \(error.localizedDescription)")return}guard let userState = userState else {return}print("The user is \(userState.rawValue).")switch userState {case .signedIn:self.initializeAppSync()// 进入主界面let home = HomeViewController()let navCtrl = UINavigationController(rootViewController: home)self.window?.rootViewController = navCtrlself.window?.makeKeyAndVisible()breakdefault://界面跳转let login = LoginViewController()self.window?.rootViewController = loginbreak}}

HomeViewController.swift

首先导入包

import AWSAppSync
import Amplify
import AmplifyPlugins
import SnapKit

关键代码获取 appSyncClient


guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}appSyncClient = appDelegate.appSyncClient

还有注意 sensor-id:要去你自己的项目中查找

到此iOS代码已经结束请查看demo中的代码段

模拟温度探头的

进入项目中的 sensor文件中打开 create-senor.js文件

安装Node.js软件包,并运行Node.js应用程序,在AWS IoT Core中将传感器创建为Thing。它还将创建并安装传感器对物联网核心进行身份验证所需的证书。

从传感器文件夹中:

$ npm install
$ node create-sensor.js

*注意-这将使用您的默认AWS配置文件帐户和地区创建传感器。如果您没有在本地AWS配置中指定默认区域,它将默认为us-east-1。

如果您没有默认配置文件或使用的不是默认配置文件,请使用指定要使用的配置文件名称的AWS_PROFILE环境变量运行该应用程序。

将[my-aws-profile]替换为您的个人资料名称:

$ AWS_PROFILE=[my-aws-profile] node create-sensor.js

特别注意 :修改 //AWS_PROFILE=my-aws-profile node create-sensor.js
const PROFILE = process.env.AWS_PROFILE || ‘rnd’; 改成你自己命名的 因为这个与你的 accesskey是对应的

运行如下代码:


The default interactive shell is now zsh.
To update your account to use zsh, please run `chsh -s /bin/zsh`.
For more details, please visit https://support.apple.com/kb/HT208050.
ThermodeiMac:AWSServeiceTemperature rnd$ cd sensor
ThermodeiMac:sensor rnd$ node index.js
connected to IoT Hub
published to shadow topic $aws/things/sensor-1669959587928/shadow/update {"state":{"reported":{"sensorType":"Temperature"}}}
published to topic dt/sensor-view/sensor-1669959587928/sensor-value {"value":82,"timestamp":1669959722472}

结束

现在打开ios app 运行即可以看到以下界面
请添加图片描述
请添加图片描述
项目地址源代码在 https://github.com/ArdWang/AWSServeiceTemperature
欢迎查看给个star吧

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...
有效的括号 一、题目 给定一个只包括 '(',')','{','}'...
【Ctfer训练计划】——(三... 作者名:Demo不是emo  主页面链接:主页传送门 创作初心ÿ...