aws-appsync-iot-core-实时iOS端示例
第一步参考如下资料
- 第一步找资料
网址: 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/
第二步搭建项目
准备工作
- 首先打开xcode创建项目 使用的是 Amplify v1 版本记住不要使用错了
项目的参数设置如下:
Product Name: input AmplifyDemo
Interface: select Storyboard
Language: Swift
点击next选择自己适合的位置
- 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 ttys001
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:~ 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 frameworks
use_frameworks!
# Pods for RilCompanySensor
pod '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项目部分已经结束
- 打开我创建的项目下载下来里面有一个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 Code
Using 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: d1jvkcwlhw9pvm
Deployment 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 <category>" 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 cloud
Pro tip:
Try "amplify add api" to create a backend API and then "amplify push" to deploy everything
ThermodeiMac:AmplifyDemo rnd$
(6) 创建的部分已经完成然后接下来还差一步就成功了继续在终端输入 sudo amplify push
Pro tip:
Try "amplify add api" to create a backend API and then "amplify push" to deploy everything
ThermodeiMac: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/6
amplify-amplifydemo-dosandbox… AWS::CloudFormation::Stack UPDATE_COMPLETE Fri Dec 02 2022 1
authsensorview74d21f87 AWS::CloudFormation::Stack CREATE_COMPLETE Fri Dec 02 2022 1
functiongetsensor AWS::CloudFormation::Stack CREATE_COMPLETE Fri Dec 02 2022 1
apisensorview AWS::CloudFormation::Stack CREATE_COMPLETE Fri Dec 02 2022 1
functioncreatesensorvalue AWS::CloudFormation::Stack CREATE_COMPLETE Fri Dec 02 2022 1
iotrulecreatesensorvalue AWS::CloudFormation::Stack CREATE_COMPLETE Fri Dec 02 2022 1
Deployed auth sensorview74d21f87 [ ======================================== ] 11/11
SNSRole AWS::IAM::Role CREATE_COMPLETE Fri Dec 02 2022 1
UserPool AWS::Cognito::UserPool CREATE_COMPLETE Fri Dec 02 2022 1
UserPoolClient AWS::Cognito::UserPoolClient CREATE_COMPLETE Fri Dec 02 2022 1
UserPoolClientWeb AWS::Cognito::UserPoolClient CREATE_COMPLETE Fri Dec 02 2022 1
UserPoolClientRole AWS::IAM::Role CREATE_COMPLETE Fri Dec 02 2022 1
UserPoolClientLambda AWS::Lambda::Function CREATE_COMPLETE Fri Dec 02 2022 1
UserPoolClientLambdaPolicy AWS::IAM::Policy CREATE_COMPLETE Fri Dec 02 2022 1
UserPoolClientLogPolicy AWS::IAM::Policy CREATE_COMPLETE Fri Dec 02 2022 1
UserPoolClientInputs Custom::LambdaCallout CREATE_COMPLETE Fri Dec 02 2022 1
IdentityPool AWS::Cognito::IdentityPool CREATE_COMPLETE Fri Dec 02 2022 1
IdentityPoolRoleMap AWS::Cognito::IdentityPoolRol… CREATE_COMPLETE Fri Dec 02 2022 1
Deployed function getsensor [ ======================================== ] 3/3
Deployed function createsensorvalue [ ======================================== ] 4/4
LambdaExecutionRole AWS::IAM::Role CREATE_COMPLETE Fri Dec 02 2022 1
LambdaFunction AWS::Lambda::Function CREATE_COMPLETE Fri Dec 02 2022 1
lambdaexecutionpolicy AWS::IAM::Policy CREATE_COMPLETE Fri Dec 02 2022 1
AmplifyResourcesPolicy AWS::IAM::Policy CREATE_COMPLETE Fri Dec 02 2022 1
Deployed iotrule createsensorvalue [ ======================================== ] 2/2
CreateSensorValueRule AWS::IoT::TopicRule CREATE_COMPLETE Fri Dec 02 2022 1
createsensorvalueallowIOTRule… AWS::Lambda::Permission CREATE_COMPLETE Fri Dec 02 2022 1
✔ Generated GraphQL operations successfully and saved at graphql
✖ EISDIR: illegal operation on a directory, read
GraphQL endpoint: https://xxxxxxxxx.appsync-api.us-east-1.amazonaws.com/graphql
GraphQL transformer version: 1
ThermodeiMac: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项目
目前为止你的项目配置已经全部完成接下来进入项目部分
- 进入AmplifyDemo 打开iOS项目 请选择 AmplifyDemo.xcworkspace
进入到项目中选择添加文件到项目 请选择“Add files to AmplifyDemo” 如下图所示 把 amplifyconfiguration 和 awsconfiguration 一起放入添加到项目中
然后再根据以上的添加方法把 amplify里面生成的generated的文件的models导入到你的项目中去
还有一个生成的 ApiHelp.swift一并导入项目
如图所示:
- 创建iOS的代码
此代码不重要的地方略过…
首先打开 AppDelegate.swift 导入包
import AWSAppSync
import Amplify
import AmplifyPlugins
import AWSMobileClient
然后接下添加注册
do{
Amplify.Logging.logLevel = .verbose
try 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) in
if 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 = navCtrl
self.window?.makeKeyAndVisible()
break
default:
//界面跳转
let login = LoginViewController()
self.window?.rootViewController = login
break
}
}
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吧