今天接到需求要在LaunchScreen显示版本号,然额,LaunchScreen.stortboard 里面的文本必须是静态的,每次在pubspec.yaml修改版本号后还要手动修改LaunchScreen.stortboard,打包几回后决定将其作成自动化的。
ios
复制代码
参考了stackoverflow的思路,不过又和纯ios项目不太同样,脚本打算用dart 来写。基本就是读取pubspec.yaml文件中的版本号,而后替换LaunchScreen.stortboard文件swift
replace_launch_screen.dart
xcode
import 'dart:io';
main() {
File launchScreenFile = File("../ios/Runner/Base.lproj/LaunchScreen.storyboard");
File pubSpecFile = File("../pubspec.yaml");
// 1.从pubspec读取版本号
String pubSpecFileContent = pubSpecFile.readAsStringSync();
RegExp versionReg = new RegExp("[\r\n]\\s*version:\\s*(\\S+)\\+(\\d+)");
RegExpMatch versionMatch = versionReg.firstMatch(pubSpecFileContent);
print(versionMatch.group(1) + ":" + versionMatch.group(2));
// 2.从lauchScreen获取替换字符串
String launchScreenFileContent = launchScreenFile.readAsStringSync();
// print(launchScreenFileContent);
RegExp versionTextReg = new RegExp('text="\\S+"');
RegExpMatch versionTextMatch = versionTextReg.firstMatch(launchScreenFileContent);
// print(versionReg.hasMatch(launchScreenFileContent));
print(versionTextMatch.group(0));
String strToBeReplaced = versionTextMatch.group(0);
String replacedLacunchScreen = launchScreenFileContent.replaceFirst(versionTextReg, "text=\"${versionMatch.group(1)}\"");
launchScreenFile.writeAsString(replacedLacunchScreen, mode: FileMode.writeOnly);
}
复制代码
"$FLUTTER_ROOT/bin/cache/dart-sdk/bin/dart" ../scripts/replace_launch_screen.dart 复制代码
整体来讲代码简单,步骤也不复杂,不过用dart 来替换,和项目代码保持统一了,通俗易懂,须要的能够参考一下。bash