capacitor-plugin-spm-support
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAdd SPM Support to a Capacitor Plugin
为Capacitor插件添加SPM支持
Add Swift Package Manager (SPM) support to an existing Capacitor plugin by replacing the Objective-C bridge with the Swift protocol and adding a manifest.
CAPBridgedPluginPackage.swift通过使用 Swift协议替换Objective-C桥接文件并添加清单,为现有Capacitor插件添加Swift Package Manager (SPM) 支持。
CAPBridgedPluginPackage.swiftPrerequisites
前提条件
| Requirement | Version |
|---|---|
| Capacitor | 6+ |
| Swift | 5.9+ |
| Xcode | 15+ |
The project must be a Capacitor plugin (not an app project). The plugin must have an existing iOS implementation with Swift source files in .
ios/Plugin/| 要求 | 版本 |
|---|---|
| Capacitor | 6+ |
| Swift | 5.9+ |
| Xcode | 15+ |
项目必须是Capacitor 插件(而非应用项目)。插件必须已有iOS实现,且Swift源文件位于目录下。
ios/Plugin/Procedures
操作步骤
Step 1: Gather Plugin Information
步骤1:收集插件信息
- Read in the plugin root. Extract:
package.json- The plugin package name (e.g., ).
@capawesome/capacitor-app-review - The existing array entries.
files - The existing entries.
scripts
- The plugin package name (e.g.,
- Read the file in the plugin root. Extract:
.podspec- The pod name (the argument, e.g.,
Pod::Spec.new). This becomes the SPM package name.CapawesomeCapacitorAppReview - The iOS deployment target from (e.g.,
s.ios.deployment_target). Extract the major version number (e.g.,'13.0'). This becomes the SPM iOS version.13 - All third-party CocoaPods dependencies — any or
s.dependencyentries that are notspec.dependencyorCapacitor. Record each dependency name and version constraint.CapacitorCordova
- The pod name (the
- Identify the plugin Swift file in . It contains a class extending
ios/Plugin/withCAPPlugin. Extract:@objc(<PluginClassName>)- The plugin class name (e.g., ).
AppReviewPlugin - The JavaScript name from the Objective-C file's
.mmacro first string argument (e.g.,CAP_PLUGIN).AppReview - All plugin methods from macro calls in the
CAP_PLUGIN_METHODfile, noting each method's name and return type (e.g.,.m).CAPPluginReturnPromise
- The plugin class name (e.g.,
- Identify the Objective-C bridge files in :
ios/Plugin/- (header file)
<PluginClassName>.h - (implementation file with
<PluginClassName>.mmacro)CAP_PLUGIN
- Read the Capacitor peer dependency version from (
package.json). Determine the major version (e.g.,peerDependencies["@capacitor/core"]). This is the Capacitor major version.6
- 读取插件根目录下的,提取:
package.json- 插件包名称(例如:)。
@capawesome/capacitor-app-review - 现有数组条目。
files - 现有条目。
scripts
- 插件包名称(例如:
- 读取插件根目录下的文件,提取:
.podspec- Pod名称(的参数,例如:
Pod::Spec.new),此名称将作为SPM包名称。CapawesomeCapacitorAppReview - 从中提取的iOS部署目标(例如:
s.ios.deployment_target),取主版本号(例如:'13.0')作为SPM iOS版本。13 - 所有第三方CocoaPods依赖 —— 所有非或
Capacitor的CapacitorCordova或s.dependency条目,记录每个依赖的名称和版本约束。spec.dependency
- Pod名称(
- 定位目录下的插件Swift文件,该文件包含一个继承自
ios/Plugin/且带有CAPPlugin的类,提取:@objc(<PluginClassName>)- 插件类名称(例如:)。
AppReviewPlugin - Objective-C 文件中
.m宏第一个字符串参数中的JavaScript名称(例如:CAP_PLUGIN)。AppReview - 文件中
.m宏调用的所有插件方法,记录每个方法的名称和返回类型(例如:CAP_PLUGIN_METHOD)。CAPPluginReturnPromise
- 插件类名称(例如:
- 定位目录下的Objective-C桥接文件:
ios/Plugin/- (头文件)
<PluginClassName>.h - (包含
<PluginClassName>.m宏的实现文件)CAP_PLUGIN
- 从中读取Capacitor对等依赖版本(
package.json),确定主版本(例如:peerDependencies["@capacitor/core"]),此为Capacitor主版本。6
Step 2: Resolve CocoaPods Dependencies for SPM
步骤2:为SPM解析CocoaPods依赖
Skip this step if no third-party CocoaPods dependencies were found in Step 1.
For each third-party CocoaPods dependency, an equivalent SPM-compatible package is needed. Present the list of dependencies to the user and ask whether they can provide the SPM package URLs themselves, or whether the agent should search the web for SPM equivalents.
If the user provides SPM package URLs: Record them and proceed to Step 3.
If the user requests a web search: For each CocoaPods dependency:
- Search the web for to determine whether the original CocoaPods dependency also supports SPM. Many popular libraries (e.g., Firebase, Alamofire) distribute via both CocoaPods and SPM from the same repository.
"<dependency_name>" Swift Package Manager - If the original library supports SPM, use its Git repository URL. Use the same version as specified in the podspec — convert the CocoaPods version constraint to the SPM equivalent (e.g., becomes
~> 5.0,.upToNextMajor(from: "5.0.0")becomes= 2.1.0)..exact("2.1.0") - If the original library does not support SPM, search for to find a replacement package that provides equivalent functionality via SPM. Use a version that is compatible with the version used in the podspec.
"<dependency_name>" SPM alternative - If no SPM-compatible alternative exists, inform the user and ask how to proceed.
Record the resolved SPM package URL, version requirement, and product name(s) for each dependency. These will be added to in the next step.
Package.swift如果步骤1中未找到第三方CocoaPods依赖,可跳过此步骤。
对于每个第三方CocoaPods依赖,需要找到对应的SPM兼容包。将依赖列表展示给用户,询问他们是否能自行提供SPM包URL,或是需要助手在网上搜索等效的SPM包。
如果用户提供SPM包URL: 记录URL并进入步骤3。
如果用户要求进行网络搜索: 对于每个CocoaPods依赖:
- 在网上搜索,判断原CocoaPods依赖是否也支持SPM。许多热门库(例如Firebase、Alamofire)会通过同一仓库同时发布CocoaPods和SPM版本。
"<dependency_name>" Swift Package Manager - 如果原库支持SPM,使用其Git仓库URL。使用与podspec中指定的相同版本 —— 将CocoaPods版本约束转换为SPM等效格式(例如:转换为
~> 5.0,.upToNextMajor(from: "5.0.0")转换为= 2.1.0)。.exact("2.1.0") - 如果原库不支持SPM,搜索以找到提供等效功能的SPM替代包,使用与podspec中版本兼容的版本。
"<dependency_name>" SPM alternative - 如果找不到SPM兼容的替代包,告知用户并询问后续处理方式。
记录每个依赖已解析的SPM包URL、版本要求和产品名称,这些将在下一步添加到中。
Package.swiftStep 3: Create Package.swift
Package.swift步骤3:创建Package.swift
Package.swiftCreate in the plugin root directory with the following content:
Package.swiftswift
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "<SPM_PACKAGE_NAME>",
platforms: [.iOS(.v<SPM_IOS_VERSION>)],
products: [
.library(
name: "<SPM_PACKAGE_NAME>",
targets: ["<PLUGIN_CLASS_NAME>"])
],
dependencies: [
.package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", branch: "<CAPACITOR_MAJOR_VERSION>.0.0")
// <ADDITIONAL_PACKAGE_DEPENDENCIES>
],
targets: [
.target(
name: "<PLUGIN_CLASS_NAME>",
dependencies: [
.product(name: "Capacitor", package: "capacitor-swift-pm"),
.product(name: "Cordova", package: "capacitor-swift-pm")
// <ADDITIONAL_TARGET_DEPENDENCIES>
],
path: "ios/Plugin"),
.testTarget(
name: "<PLUGIN_CLASS_NAME>Tests",
dependencies: ["<PLUGIN_CLASS_NAME>"],
path: "ios/PluginTests")
]
)Replace all placeholders:
- — the SPM iOS version from Step 1 (e.g.,
<SPM_IOS_VERSION>).13 - — the pod name from Step 1 (e.g.,
<SPM_PACKAGE_NAME>).CapawesomeCapacitorAppReview - — the plugin class name from Step 1 (e.g.,
<PLUGIN_CLASS_NAME>).AppReviewPlugin - — the Capacitor major version from Step 1 (e.g.,
<CAPACITOR_MAJOR_VERSION>).6 - — if third-party dependencies were resolved in Step 2, add a
<ADDITIONAL_PACKAGE_DEPENDENCIES>entry for each. Remove the comment line if no extra dependencies exist..package(url: "<repo_url>", <version_requirement>) - — for each package dependency added above, add a corresponding
<ADDITIONAL_TARGET_DEPENDENCIES>entry. Remove the comment line if no extra dependencies exist..product(name: "<ProductName>", package: "<package-name>")
在插件根目录下创建,内容如下:
Package.swiftswift
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "<SPM_PACKAGE_NAME>",
platforms: [.iOS(.v<SPM_IOS_VERSION>)],
products: [
.library(
name: "<SPM_PACKAGE_NAME>",
targets: ["<PLUGIN_CLASS_NAME>"])
],
dependencies: [
.package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", branch: "<CAPACITOR_MAJOR_VERSION>.0.0")
// <ADDITIONAL_PACKAGE_DEPENDENCIES>
],
targets: [
.target(
name: "<PLUGIN_CLASS_NAME>",
dependencies: [
.product(name: "Capacitor", package: "capacitor-swift-pm"),
.product(name: "Cordova", package: "capacitor-swift-pm")
// <ADDITIONAL_TARGET_DEPENDENCIES>
],
path: "ios/Plugin"),
.testTarget(
name: "<PLUGIN_CLASS_NAME>Tests",
dependencies: ["<PLUGIN_CLASS_NAME>"],
path: "ios/PluginTests")
]
)替换所有占位符:
- —— 步骤1中获取的SPM iOS版本(例如:
<SPM_IOS_VERSION>)。13 - —— 步骤1中获取的Pod名称(例如:
<SPM_PACKAGE_NAME>)。CapawesomeCapacitorAppReview - —— 步骤1中获取的插件类名称(例如:
<PLUGIN_CLASS_NAME>)。AppReviewPlugin - —— 步骤1中获取的Capacitor主版本(例如:
<CAPACITOR_MAJOR_VERSION>)。6 - —— 如果步骤2中解析了第三方依赖,为每个依赖添加
<ADDITIONAL_PACKAGE_DEPENDENCIES>条目。如果没有额外依赖,删除此注释行。.package(url: "<repo_url>", <version_requirement>) - —— 为上述添加的每个包依赖,添加对应的
<ADDITIONAL_TARGET_DEPENDENCIES>条目。如果没有额外依赖,删除此注释行。.product(name: "<ProductName>", package: "<package-name>")
Step 4: Update the Swift Plugin Class
步骤4:更新Swift插件类
Open the plugin Swift file (e.g., ).
ios/Plugin/<PluginClassName>.swift- Add protocol conformance to the class declaration.
CAPBridgedPlugin - Add the three required properties as the first properties in the class body, before any existing properties.
Apply this diff pattern:
diff
@objc(<PluginClassName>)
-public class <PluginClassName>: CAPPlugin {
+public class <PluginClassName>: CAPPlugin, CAPBridgedPlugin {
+ public let identifier = "<PluginClassName>"
+ public let jsName = "<JS_NAME>"
+ public let pluginMethods: [CAPPluginMethod] = [
+ CAPPluginMethod(name: "<method1>", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "<method2>", returnType: CAPPluginReturnPromise)
+ ]Replace:
- — the plugin class name (e.g.,
<PluginClassName>).AppReviewPlugin - — the JavaScript name from the
<JS_NAME>file's.mmacro (e.g.,CAP_PLUGIN).AppReview - The array — list all methods from the
pluginMethodsfile's.mcalls, preserving each method's name and return type exactly.CAP_PLUGIN_METHOD
打开插件Swift文件(例如:)。
ios/Plugin/<PluginClassName>.swift- 为类声明添加协议一致性。
CAPBridgedPlugin - 在类体的最前面添加三个必需的属性,位于所有现有属性之前。
应用如下差异模式:
diff
@objc(<PluginClassName>)
-public class <PluginClassName>: CAPPlugin {
+public class <PluginClassName>: CAPPlugin, CAPBridgedPlugin {
+ public let identifier = "<PluginClassName>"
+ public let jsName = "<JS_NAME>"
+ public let pluginMethods: [CAPPluginMethod] = [
+ CAPPluginMethod(name: "<method1>", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "<method2>", returnType: CAPPluginReturnPromise)
+ ]替换:
- —— 插件类名称(例如:
<PluginClassName>)。AppReviewPlugin - ——
<JS_NAME>文件中.m宏的JavaScript名称(例如:CAP_PLUGIN)。AppReview - 数组 —— 列出
pluginMethods文件中.m调用的所有方法,严格保留每个方法的名称和返回类型。CAP_PLUGIN_METHOD
Step 5: Delete Objective-C Bridge Files
步骤5:删除Objective-C桥接文件
Delete the following files from :
ios/Plugin/<PluginClassName>.h<PluginClassName>.m
These are no longer needed because the plugin registration is now handled by the protocol in Swift.
CAPBridgedPlugin从目录中删除以下文件:
ios/Plugin/<PluginClassName>.h<PluginClassName>.m
这些文件不再需要,因为现在插件注册由Swift中的协议处理。
CAPBridgedPluginStep 6: Clean Up the Xcode Project File
步骤6:清理Xcode项目文件
Open and remove all references to the deleted Objective-C files. Specifically, remove lines referencing:
ios/Plugin.xcodeproj/project.pbxproj- — file references, build phase entries (
<PluginClassName>.h,PBXBuildFile,PBXFileReferencechildren,PBXGroup)PBXHeadersBuildPhase - — file references, build phase entries (
<PluginClassName>.m,PBXBuildFile,PBXFileReferencechildren,PBXGroup)PBXSourcesBuildPhase
Search for both filenames in the file and remove every line that references them.
.pbxproj打开,移除所有已删除Objective-C文件的引用。具体来说,移除引用以下内容的行:
ios/Plugin.xcodeproj/project.pbxproj- —— 文件引用、构建阶段条目(
<PluginClassName>.h、PBXBuildFile、PBXFileReference子项、PBXGroup)PBXHeadersBuildPhase - —— 文件引用、构建阶段条目(
<PluginClassName>.m、PBXBuildFile、PBXFileReference子项、PBXGroup)PBXSourcesBuildPhase
在文件中搜索这两个文件名,移除所有引用它们的行。
.pbxprojStep 7: Update .gitignore
.gitignore步骤7:更新.gitignore
.gitignoreOpen in the plugin root. Add the following entries if not already present:
.gitignorediff
# iOS files
+Package.resolved
+/.build
+/Packages
+.swiftpm/configuration/registries.json
+.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
+.netrcPlace these entries in the iOS section of the file, after any existing iOS-related entries (e.g., , ).
.gitignorePodsPodfile.lock打开插件根目录下的,如果以下条目尚未存在,添加它们:
.gitignorediff
# iOS files
+Package.resolved
+/.build
+/Packages
+.swiftpm/configuration/registries.json
+.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
+.netrc将这些条目放在的iOS部分,位于所有现有iOS相关条目之后(例如、)。
.gitignorePodsPodfile.lockStep 8: Update package.json
package.json步骤8:更新package.json
package.jsonApply two changes to :
package.json- Add to the
"Package.swift"array:files
diff
"ios/Plugin/",
- "<PodName>.podspec"
+ "<PodName>.podspec",
+ "Package.swift"
],- Add the script to the
ios:spm:installobject:scripts
diff
"ios:pod:install": "cd ios && pod install --repo-update && cd ..",
+ "ios:spm:install": "cd ios && swift package resolve && cd ..",If the script does not exist, add the script after the last existing script entry.
ios:pod:installios:spm:install对进行两处修改:
package.json- 将添加到
"Package.swift"数组:files
diff
"ios/Plugin/",
- "<PodName>.podspec"
+ "<PodName>.podspec",
+ "Package.swift"
],- 在对象中添加
scripts脚本:ios:spm:install
diff
"ios:pod:install": "cd ios && pod install --repo-update && cd ..",
+ "ios:spm:install": "cd ios && swift package resolve && cd ..",如果脚本不存在,将脚本添加到最后一个现有脚本条目之后。
ios:pod:installios:spm:installStep 9: Verify
步骤9:验证
- Run in the plugin root to ensure
npm installis valid.package.json - Verify the iOS build still succeeds by building the plugin's example or test app.
- 在插件根目录运行,确保
npm install有效。package.json - 通过构建插件的示例或测试应用,验证iOS构建是否仍能成功。
Error Handling
错误处理
- If the file becomes corrupted after removing ObjC references, restore it from version control and carefully re-edit, ensuring only complete lines are removed.
.pbxproj - If the Swift build fails with not found, verify that
CAPBridgedPluginis version 6+ and that@capacitor/corebranch matches the Capacitor major version.capacitor-swift-pm - If SPM resolution fails (), verify the
swift package resolvetarget paths match the actual directory structure (Package.swiftfor sources,ios/Pluginfor tests).ios/PluginTests - If the plugin has no test target directory (), remove the
ios/PluginTestsblock from.testTarget.Package.swift - If the plugin has additional Swift source files beyond the main plugin file, no extra changes are needed — SPM automatically includes all files in the target path.
.swift - If the file uses
.minstead ofCAPPluginReturnNonefor some methods, preserve the original return type in theCAPPluginReturnPromisearray.pluginMethods - If a CocoaPods dependency has no SPM equivalent and no alternative can be found, the plugin cannot fully support SPM. Inform the user and suggest they either vendor the dependency source or wait for upstream SPM support.
- 如果移除ObjC引用后文件损坏,从版本控制中恢复文件并仔细重新编辑,确保只移除完整的行。
.pbxproj - 如果Swift构建失败并提示未找到,验证
CAPBridgedPlugin版本是否为6+,且@capacitor/core分支与Capacitor主版本匹配。capacitor-swift-pm - 如果SPM解析失败(),验证
swift package resolve中的目标路径是否与实际目录结构匹配(源码为Package.swift,测试为ios/Plugin)。ios/PluginTests - 如果插件没有测试目标目录(),从
ios/PluginTests中移除Package.swift块。.testTarget - 如果插件除主插件文件外还有其他Swift源文件,无需额外更改 —— SPM会自动包含目标路径下的所有文件。
.swift - 如果文件中某些方法使用
.m而非CAPPluginReturnNone,在CAPPluginReturnPromise数组中保留原始返回类型。pluginMethods - 如果某个CocoaPods依赖没有SPM等效包且找不到替代方案,该插件无法完全支持SPM。告知用户并建议他们要么将依赖源码嵌入项目,要么等待上游支持SPM。