Apache OpenWhisk 移动端 SDK(iOS/watchOS)接入与调用实战指南

发布时间:2026/10/9 2:17:52
Apache OpenWhisk 移动端 SDK(iOS/watchOS)接入与调用实战指南 后端云原生微服务【免费下载链接】openwhiskApache OpenWhisk is an open source serverless cloud platform项目地址https://gitcode.com/gh_mirrors/openw/openwhisk点击查看免费下载导读本文基于 Apache OpenWhisk 官方文档 docs/mobile_sdk.md系统讲解 OpenWhisk 移动端 SDK 的完整接入流程与核心用法。该 SDK 面向 iOS 与 watchOS 设备让移动应用可以直接触发fire远程触发器、调用invoke远程 Action是构建手机端事件上报 云端无服务器计算类应用如位置变化触发、消息推送、数据采集的标准方案。读完本文你将掌握三种 SDK 安装方式CocoaPods / Carthage / 源码编译、凭据获取与初始化、Action 调用、Trigger 触发、结果回传、baseURL 与自定义网络会话配置以及限定名qualified name解析规则和WhiskButton一键式按钮组件并理解其底层对应的 OpenWhisk REST API 调用链。一、SDK 概述能力边界与运行环境OpenWhisk 移动端 SDK 为 iOS 和 watchOS 设备提供能力使移动应用能够触发远程触发器fire remote triggers例如位置变化事件上报调用远程动作invoke remote actions例如触发云端 Action 在 OpenWhisk Console 打印消息。运行环境与版本前提以当前仓库文档为准SDK 使用 Swift 4 编写支持 iOS 11 及更高版本可使用 Xcode 9 构建 SDK。Android 说明当前没有可用的 Android 版本 SDKAndroid 开发者可以直接使用 OpenWhisk REST API详见 docs/rest_api.md实现同样的功能。补充理解SDK 的调用本质上是对 OpenWhisk Controller 暴露的 REST 接口的封装。从 core/controller/src/main/scala/whisk/core/controller/RestAPIs.scala 的路由定义可以看到Controller 将命名空间、Action、Trigger、Rule、Activation、Package 等资源统一挂载在api/v1/namespaces/...路径下并通过 Basic AuthbasicAuth(validateCredentials)进行鉴权——这与下文将要介绍的key:token 凭据 Basic Auth机制一一对应。二、把 SDK 加入你的 App三种安装方式SDK 支持三种安装方式CocoaPods、Carthage、源码编译开发者可按团队习惯任选其一。2.1 使用 CocoaPods 安装OpenWhisk 移动 SDK 通过 CocoaPods 公开发布。假设 CocoaPods 已安装在 starter app 项目目录中创建名为Podfile的文件写入以下内容install! cocoapods, :deterministic_uuids false use_frameworks! target MyApp do pod OpenWhisk, :git https://github.com/apache/incubator-openwhisk-client-swift.git, :tag 0.3.0 end target MyApp WatchKit Extension do pod OpenWhisk, :git https://github.com/apache/incubator-openwhisk-client-swift.git, :tag 0.3.0 end然后在命令行执行pod install该命令会为一个带 watchOS 扩展的 iOS 应用安装 SDK。安装完成后使用 CocoaPods 生成的 workspace 文件在 Xcode 中打开工程。常见坑Swift 版本警告安装后打开工程编译时可能出现如下警告Use Legacy Swift Language Version (SWIFT_VERSION) is required to be configured correctly for targets which use Swift. Use the [Edit Convert To Current Swift Syntax…] menu to choose a Swift version or use the Build Settings editor to configure the build setting directly.该警告的根因是CocoaPods 没有在 Pods 工程中更新 Swift 版本。修复方法有两种选中 Pods 工程中的 OpenWhisk target进入 Build Settings将Use Legacy Swift Language Version改为no或者在 Podfile 末尾追加如下 post-install 钩子post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| config.build_settings[SWIFT_VERSION] 4.0 end end end2.2 使用 Carthage 安装在 App 工程目录创建Cartfile文件写入github openwhisk/openwhisk-client-swift.git ~ 0.3.0 # Or latest version执行carthage update --platform iosCarthage 会下载并构建 SDK在工程目录下创建Carthage目录并把OpenWhisk.framework放入Carthage/build/iOS。随后需要把OpenWhisk.framework添加到 Xcode 工程的Embedded Frameworks中。2.3 从源码安装SDK 源码仓库为incubator-openwhisk-client-swift。操作步骤用 Xcode 打开工程文件OpenWhisk.xcodeproj工程包含两个 schemeOpenWhisk面向 iOS 目标OpenWhiskWatch面向 watchOS 2 目标按需构建对应 target并将生成的 framework 添加到你的 App 中产物通常在~/Library/Developer/Xcode/DerivedData/your app name目录下。三、安装官方 Starter App 示例官方提供了一个内嵌 OpenWhisk SDK framework 的 starter app 示例代码可通过 OpenWhisk CLI 下载wsk sdk install iOS该命令下载一个包含 starter app 的压缩文件工程目录内含 Podfile。接着安装 SDK 依赖pod install提示wsk sdk子命令家族不仅支持 iOS。以本仓库 docs/cli.md 为例wsk sdk install bashauto还可生成 bash 自动补全脚本wsk_cli_bash_completion.sh可见wsk sdk是 CLI 提供 SDK/工具分发的统一入口。四、快速开始凭据对象与 SDK 实例化开始调用前需要先用 OpenWhisk API 凭据创建WhiskCredentials对象再基于它创建OpenWhisk实例let credentialsConfiguration WhiskCredentials(accessKey: myKey, accessToken: myToken) let whisk Whisk(credentials: credentialsConfiguration!)其中myKey与myToken来自你的 OpenWhisk 账号。获取凭据的方式是 CLI 命令wsk property get --auth输出形如whisk auth kkkkkkkk-kkkk-kkkk-kkkk-kkkkkkkkkkkk:tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt冒号前面是 key冒号后面是 token。底层原理Controller 的鉴权正是把该 key:token 拼成 Basic Auth 凭据进行校验。参见 core/controller/src/main/scala/whisk/core/controller/Authenticate.scalavalidateCredentials将 Basic Auth 的用户名/密码解析为AuthKey(UUID, Secret)再到认证库中查询并比对。REST 层用curl -u $AUTH ...的写法与 SDK 内部行为等价参考 docs/rest_api.md其 Authorization 头即为凭据字符串的 base64 编码。五、调用远程 Action调用远程 Action 使用invokeAction方法可指定 Action 所属的 namespace也可留空使用默认命名空间通过字典向 Action 传参。示例调用一个向 OpenWhisk Console 打印消息的 Action// In this example, we are invoking an action to print a message to the OpenWhisk Console var params DictionaryString, String() params[payload] Hi from mobile do { try whisk.invokeAction(name: helloConsole, package: mypackage, namespace: mynamespace, parameters: params, hasResult: false, callback: {(reply, error) - Void in if let error error { //do something print(Error invoking action \(error.localizedDescription)) } else { print(Action invoked!) } }) } catch { print(Error \(error)) }注意示例中虽然显式传入了namespace: mynamespace但注释说明实际使用的是默认命名空间即文档原文的表述在 OpenWhisk 中默认命名空间通常用_表示。底层调用链invokeAction对应 REST 层对 Action 的 POST 激活。Controller 侧实现位于 core/controller/src/main/scala/whisk/core/controller/Actions.scalaPOST 请求体反序列化为 payload 后经过权限校验Privilege.ACTIVATE与final 参数不可覆盖检查再调用invokeAction提交给负载均衡器。非阻塞调用返回 202 activationId阻塞调用返回 200 activation JSON详情见同文件的响应注释与 docs/rest_api.md 的 curl 对照示例。六、触发远程 Trigger触发远程 Trigger 使用fireTrigger方法同样通过字典传参// In this example we are firing a trigger when our location has changed by a certain amount var locationParams DictionaryString, String() locationParams[payload] {\lat\:41.27093, \lon\:-73.77763} do { try whisk.fireTrigger(name: locationChanged, package: mypackage, namespace: mynamespace, parameters: locationParams, callback: {(reply, error) - Void in if let error error { print(Error firing trigger \(error.localizedDescription)) } else { print(Trigger fired!) } }) } catch { print(Error \(error)) }上述示例触发名为locationChanged的触发器。Trigger 被触发后会通过 Rule 级联调用与之绑定的 ActionController 侧的规则执行逻辑可在 core/controller/src/main/scala/whisk/core/controller/Triggers.scala 中看到触发成功后会逐个调用规则映射的 Actiontrigger-fired action ... invoked with activation并为级联调用构造 Action 调用 URL。REST 对照Trigger 的 POST 触发同样走api/v1/namespaces/_/triggers/name接口参考 docs/rest_api.md 中curl -X POST触发带参数 Trigger 的示例。七、使用返回结果的 Action如果 Action 会返回结果将invokeAction的hasResult设为true结果会出现在回调的reply字典中do { try whisk.invokeAction(name: actionWithResult, package: mypackage, namespace: mynamespace, parameters: params, hasResult: true, callback: {(reply, error) - Void in if let error error { //do something print(Error invoking action \(error.localizedDescription)) } else { var result reply[result] print(Got result \(result)) } }) } catch { print(Error \(error)) }默认情况下SDK 只返回 activation ID 以及被调用 Action 产生的结果。如果需要拿到整个响应对象的元数据包含 HTTP 响应状态码开启以下设置whisk.verboseReplies true补充这与 REST API 的blockingtrueresulttrue语义一致——只取response.result见 docs/rest_api.md 的对照示例返回体仅为{payload: hello John}而完整 activation JSON 则包含activationId、response.status、duration、annotations.limits等元数据docs/rest_api.md。八、配置 SDK对接任意 OpenWhisk 部署8.1 指定 baseURLSDK 默认连接https://openwhisk.ng.bluemix.net上的实例对接不同部署如本地或自建集群时用baseURL指定whisk.baseURL http://localhost:8080上例对接运行在localhost:8080的部署。从 core/controller/src/main/scala/whisk/core/controller/RestAPIs.scala 可以看到Controller 的默认服务端口正是 8080WhiskConfig.servicePort - 8080http://localhost:8080即可命中本地 Controller 的 REST API。8.2 自定义 NSURLSession自签名证书场景如需特殊的网络处理例如自建部署使用自签名证书可传入自定义NSURLSession// create a network delegate that trusts everything class NetworkUtilsDelegate: NSObject, NSURLSessionDelegate { func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) - Void) { completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)) } } // create an NSURLSession that uses the trusting delegate let session NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: NetworkUtilsDelegate(), delegateQueue:NSOperationQueue.mainQueue()) // set the SDK to use this urlSession instead of the default shared one whisk.urlSession session该示例创建一个信任一切的网络委托并把它包装进自定义 session再赋给 SDK 的urlSession属性从而绕过自签名证书校验。生产环境请务必按安全规范收紧该信任策略。项目配套实践仓库的 nginx 部署角色 ansible/roles/nginx/files/openwhisk-server-key.pem 与 ansible/roles/nginx/templates/nginx.conf.j2 表明OpenWhisk 标准部署中前端 nginx 承担 TLS 终结自建部署若自行签发证书SDK 侧通常就需要本节的自定义 session 方案。8.3 限定名Qualified Name解析规则所有 Action 和 Trigger 都有一个由namespace、package、名称组成的全限定名。SDK 既支持将这三者作为独立参数传入也提供接受形如/mynamespace/mypackage/nameOfActionOrTrigger的限定名字符串的函数。限定名支持省略 namespace 和 packageOpenWhisk 用户都有默认值解析规则如下传入 qNamenamespacepackageaction/triggerfoodefaultdefaultfoomypackage/foodefaultmypackagefoo/mynamespace/foomynamespacedefaultfoo/mynamespace/mypackage/foomynamespacemypackagefoo其余任何组合都会抛出WhiskError.QualifiedName错误因此使用限定名时必须把调用包在do/try/catch结构中见下文的 WhiskButton 示例。实体层级佐证OpenWhisk 的实体路径模型在 common/scala/src/main/scala/whisk/core/entity/EntityPath.scala 与 common/scala/src/main/scala/whisk/core/entity/FullyQualifiedEntityName.scala 中定义namespace/package/name 三级结构与 SDK 的解析规则完全对应。九、WhiskButton一键调用 Action 的按钮组件为方便使用SDK 内置WhiskButton它继承自UIButton允许按钮直接调用 Action。两种用法方式一手动触发在检测到按压事件时调用例如 IBAction 中var whiskButton WhiskButton(frame: CGRectMake(0,0,20,20)) whiskButton.setupWhiskAction(helloConsole, package: mypackage, namespace: _, credentials: credentialsConfiguration!, hasResult: false, parameters: nil, urlSession: nil) let myParams [name:value] // Call this when you detect a press event, e.g. in an IBAction, to invoke the action whiskButton.invokeAction(parameters: myParams, callback: { reply, error in if let error error { print(Oh no, error: \(error)) } else { print(Success: \(reply)) } })方式二自包含按钮按钮自己监听按压事件并调用 Action注意此处使用了限定名 API必须包在 do/try/catch 中// or alternatively you can set up a self contained button that listens for press events on itself and invokes an action var whiskButtonSelfContained WhiskButton(frame: CGRectMake(0,0,20,20)) whiskButtonSelfContained.listenForPressEvents true do { // use qualified name API which requires do/try/catch try whiskButtonSelfContained.setupWhiskAction(mypackage/helloConsole, credentials: credentialsConfiguration!, hasResult: false, parameters: nil, urlSession: nil) whiskButtonSelfContained.actionButtonCallback { reply, error in if let error error { print(Oh no, error: \(error)) } else { print(Success: \(reply)) } } } catch { print(Error setting up button \(error)) }要点归纳setupWhiskAction负责把按钮与某个 Action 绑定可传入 namespace/package 独立参数也可传入限定名字符串invokeAction(parameters:callback:)手动触发调用listenForPressEvents true时按钮自动监听按压并调用actionButtonCallback用于自包含模式下的结果回调。十、常见问题与使用建议Swift 版本警告CocoaPods 安装后如报SWIFT_VERSION警告按 2.1 节 的两种方式处理改 Build Settings 或加 post_install 钩子。自签名证书本地/内网自建部署若使用自签名证书务必配置自定义NSURLSession8.2 节并注意生产环境应替换信任一切策略为受控的证书校验。默认端点未设置baseURL时 SDK 连接https://openwhisk.ng.bluemix.net对接自建集群必须显式设置。hasResult 与 verboseReplieshasResult true拿到 Action 结果verboseReplies true获取包含 HTTP 状态码在内的完整响应元数据。限定名错误限定名格式非法时会抛WhiskError.QualifiedName务必使用 do/try/catch 包裹。Android 开发者当前无官方 Android SDK直接使用 docs/rest_api.md 中的 REST APIPUT/POST/DELETE Basic Auth即可获得与移动 SDK 等价的能力。延伸阅读docs/rest_api.mdREST API 完整参考含 Action 创建、阻塞/非阻塞调用、Trigger 触发、Rule 启停等 curl 示例docs/cli.mdwskCLI 使用指南含wsk sdk install系列命令docs/actions.md、docs/triggers_rules.mdAction 与 Trigger/Rule 概念详解Controller 侧 REST 路由定义core/controller/src/main/scala/whisk/core/controller/RestAPIs.scalaAction 激活实现core/controller/src/main/scala/whisk/core/controller/Actions.scala规则级联调用实现core/controller/src/main/scala/whisk/core/controller/Triggers.scala凭据鉴权实现core/controller/src/main/scala/whisk/core/controller/Authenticate.scala实体层级模型common/scala/src/main/scala/whisk/core/entity/EntityPath.scala。赞分享后端云原生微服务【免费下载链接】openwhiskApache OpenWhisk is an open source serverless cloud platform项目地址https://gitcode.com/gh_mirrors/openw/openwhisk点击查看免费下载相关推荐OneUptime 移动端 RUM 接入指南为 Android、iOS 与 React Native 应用接入移动端真实用户监控OneUptime 移动端 RUM 接入指南为 Android、iOS 与 React Native 应用接入移动端真实用户监控 本文是 OneUptime可观测性后端运维前端云原生微服务AI AgentApache OpenWhisk Java 动作Action开发实战从 JAR 打包到云端调用Apache OpenWhisk Java 动作Action开发实战从 JAR 打包到云端调用 Java 是 Apache OpenWhisk 官方支持的后端云原生微服务Apache APISIX openwhisk 插件实战将 Apache OpenWhisk 无服务器函数接入 API 网关Apache APISIX openwhisk 插件实战将 Apache OpenWhisk 无服务器函数接入 API 网关 本指南系统讲解 Apache AAPI网关后端云原生微服务上一篇如何在5分钟内为网易云音乐安装插件BetterNCM-Installer完整教程下一篇如何用YaeAchievement实现原神成就数据的高效导出与标准化管理创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考