在应用中升级 Capacitor 至 2.0
Capacitor 2 进行了一些工具链更新,包括在 iOS 中采用 Swift 5,并在 Android 中采用 AndroidX。
更新 Capacitor 依赖项
首先,更新 Capacitor Core 和 CLI:
npm install @capacitor/cli@2 @capacitor/core@2
接下来,更新你使用的每个 Capacitor 平台:
# iOS
npm install @capacitor/ios@2
npx cap sync ios
# Android
npm install @capacitor/android@2
npx cap sync android
# Electron
cd electron
npm install @capacitor/electron@2
不向后兼容的插件变更
- 相机
- 所有平台上的
saveToGallery默认值现在改为false - 如果
allowEditing为true且编辑被取消,将返回原始图片
- 所有平台上的
- 推送通知
- 调用
register()时不再请求权限,请使用requestPermission() PushNotificationChannel重命名为NotificationChannel
- 调用
- 本地通知
- 调用
register()时不再请求权限,请使用requestPermission() schedule()现在返回LocalNotificationScheduleResult
- 调用
- Toast
- 统一各平台的显示时长:短时间 2000 毫秒,长时间 3500 毫秒
- 地理位置
- 在 Android 上使用 Fused Location Provider
- 从
GeolocationOptions中移除了requireAltitude - 更改了 iOS 上的原生定位精度数值(更多信息)
- 文件系统
- 从
MkdirOptions中移除了createIntermediateDirectories(改用recursive) - 为 writeFile 添加了
recursive选项,这将改变 Android 和 Web 上的行为(更多信息) - 移除了
Application目录选项,因为其功能已损坏
- 从
- 设备
- 从
getInfo()中移除了batteryLevel和isCharging,请使用getBatteryInfo()
- 从
- 模态框
inputPlaceholder现在设置占位符而非文本,请改用inputText
- 应用
AppRestoredResult现在变为可选,仅在成功时返回,否则返回错误
- 剪贴板
- 移除了
ReadOptions
- 移除了
iOS
Capacitor 2 需要 Xcode 11 或更高版本。
将原生项目更新至 Swift 5
Capacitor 2 使用 Swift 5。建议将你的原生项目也更新至 Swift 5。
- 在 Xcode 中点击 编辑 -> 转换 -> 转换为当前 Swift 语法。
- App.app 将显示为选中状态,点击 下一步 按钮。
- 随后会提示 无需更改源代码。
- 最后,点击 更新 按钮。
Android
AndroidX
Capacitor 2 遵循 Google 的建议,使用 AndroidX 作为 Android 支持库依赖,因此原生项目也需要更新以使用 AndroidX。
在 Android Studio 中执行 重构 -> 迁移至 AndroidX。然后点击 迁移 按钮,最后点击 执行重构。
如果使用的 Cordova 或 Capacitor 插件尚未支持 AndroidX,可以使用 jetifier 工具对其进行修补。
npm install jetifier
npx jetifier
若要在每次包安装后自动运行,可在 package.json 中添加 "postinstall": "jetifier"。
创建通用变量
创建 android/variables.gradle 文件,内容如下:
ext {
minSdkVersion = 21
compileSdkVersion = 29
targetSdkVersion = 29
androidxAppCompatVersion = '1.1.0'
androidxCoreVersion = '1.2.0'
androidxMaterialVersion = '1.1.0-rc02'
androidxBrowserVersion = '1.2.0'
androidxLocalbroadcastmanagerVersion = '1.0.0'
firebaseMessagingVersion = '20.1.2'
playServicesLocationVersion = '17.0.0'
junitVersion = '4.12'
androidxJunitVersion = '1.1.1'
androidxEspressoCoreVersion = '3.2.0'
cordovaAndroidVersion = '7.0.0'
}
在 android/build.gradle 文件中,添加 apply from: "variables.gradle":
classpath 'com.android.tools.build:gradle:4.1.1'
classpath 'com.google.gms:google-services:4.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
+apply from: "variables.gradle"
allprojects {
repositories {
google()
jcenter()