fastlane自动化系列iOS开发

iOS开发fastlane从入门到入土(一):自动打包

2019-03-18  本文已影响0人  不会算卦的杨大仙
fastlane

Fastlane是一套使用Ruby写的自动化工具集,旨在简化Android和iOS的部署过程,自动化你的工作流。它可以简化一些乏味、单调、重复的工作,像截图、代码签名以及发布App。命令一时爽,一直命令一直爽。当你发现可以随心所欲的一行命令打包时,你就会发现fastlane有多爽了。

小插曲:之前用的2.117版本因为terminal-notifier版本过低导致本地通知无效的bug,就去提了issue,第三天就解决发布了新版本,效率真的高啊👍
本文基于fastlane-2.118.0

一、Fastlane的安装和初始化

[✔] Looking for iOS and Android projects in current directory...
[10:42:32]: Created new folder './fastlane'.
[10:42:32]: Detected an iOS/macOS project in the current directory: 'NearChargeCompany.xcworkspace'
[10:42:32]: -----------------------------
[10:42:32]: --- Welcome to fastlane 🚀 ---
[10:42:32]: -----------------------------
[10:42:32]: fastlane can help you with all kinds of automation for your mobile app
[10:42:32]: We recommend automating one task first, and then gradually automating more over time
[10:42:32]: What would you like to use fastlane for?
1. 📸  Automate screenshots  --自动化截图 (基于UITests)
2. 👩‍✈️  Automate beta distribution to TestFlight --将测试版分发到TestFlight
3. 🚀  Automate App Store distribution --自动上传、发布到App Store
4. 🛠  Manual setup - manually setup your project to automate your tasks --手动设置 - 手动设置您的项目以使您的任务自动化

这里我选择“3”-发布到Appstore
输入开发者账号与密码,如果开启两部验证需要输入安全码

[10:54:25]: --------------------------------
[10:54:25]: --- Login with your Apple ID ---
[10:54:25]: --------------------------------
[10:54:25]: To use App Store Connect and Apple Developer Portal features as part of fastlane,
[10:54:25]: we will ask you for your Apple ID username and password
[10:54:25]: This is necessary for certain fastlane features, for example:
[10:54:25]: 
[10:54:25]: - Create and manage your provisioning profiles on the Developer Portal
[10:54:25]: - Upload and manage TestFlight and App Store builds on App Store Connect
[10:54:25]: - Manage your App Store Connect app metadata and screenshots
[10:54:25]: 
[10:54:25]: Your Apple ID credentials will only be stored in your Keychain, on your local machine
[10:54:25]: For more information, check out
[10:54:25]:     https://github.com/fastlane/fastlane/tree/master/credentials_manager
[10:54:25]: 
[10:54:25]: Please enter your Apple ID developer credentials
[10:54:25]: Apple ID Username:
xx@xxx.com
[10:55:29]: Logging in...
Available session is not valid any more. Continuing with normal login.
Two-factor Authentication (6 digits code) is enabled for account 'xx@xxx.com'
More information about Two-factor Authentication: https://support.apple.com/en-us/HT204915

If you're running this in a non-interactive session (e.g. server or CI)
check out https://github.com/fastlane/fastlane/tree/master/spaceship#2-step-verification

(Input `sms` to escape this prompt and select a trusted phone number to send the code as a text message)
Please enter the 6 digit code:
260449
Requesting session...
[10:55:58]: ✅  Logging in with your Apple ID was successful

选择允许fastlane管理ITC上的元数据后,会将ITC上的所有元数据与截图下载到metadatascreenshots文件夹

[10:56:08]: Would you like fastlane to manage your app's metadata? (y/n)
y

这一步肯定会创建AppfileFastfile。如果Deliverfilescreenshotsmetadata目录没被创建,可以运行deliver init来创建。下载iTC上的截图deliver download_screenshots,下载iTC上的元数据 deliver download_metadata

Fastlane初始化完成后,工程根目录下会生成 fastlane文件夹,结构如下:

fastlane
├── Appfile
├── Deliverfile
├── Fastfile
├── metadata
│   ├── app_icon.jpg
│   ├── copyright.txt
│   ├── primary_category.txt
│   ├── primary_first_sub_category.txt
│   ├── primary_second_sub_category.txt
│   ├── review_information
│   │   ├── demo_password.txt
│   │   ├── demo_user.txt
│   │   ├── email_address.txt
│   │   ├── first_name.txt
│   │   ├── last_name.txt
│   │   ├── notes.txt
│   │   └── phone_number.txt
│   ├── secondary_category.txt
│   ├── secondary_first_sub_category.txt
│   ├── secondary_second_sub_category.txt
│   ├── trade_representative_contact_information
│   │   ├── address_line1.txt
│   │   ├── address_line2.txt
│   │   ├── address_line3.txt
│   │   ├── city_name.txt
│   │   ├── country.txt
│   │   ├── email_address.txt
│   │   ├── first_name.txt
│   │   ├── is_displayed_on_app_store.txt
│   │   ├── last_name.txt
│   │   ├── phone_number.txt
│   │   ├── postal_code.txt
│   │   ├── state.txt
│   │   └── trade_name.txt
│   └── zh-Hans
│       ├── description.txt
│       ├── keywords.txt
│       ├── marketing_url.txt
│       ├── name.txt
│       ├── privacy_url.txt
│       ├── promotional_text.txt
│       ├── release_notes.txt
│       ├── subtitle.txt
│       └── support_url.txt
└── screenshots
    ├── README.txt
    └── zh-Hans
        ├── 1_iphone6Plus_1.Simulator\ Screen\ Shot\ -\ iPhone\ 8\ Plus\ -\ 2018-06-01\ at\ 17.21.05.png
        ├── 2_iphone6Plus_2.Simulator\ Screen\ Shot\ -\ iPhone\ 8\ Plus\ -\ 2018-06-01\ at\ 17.21.29.png
        ├── 3_iphone6Plus_3.Simulator\ Screen\ Shot\ -\ iPhone\ 8\ Plus\ -\ 2018-06-01\ at\ 17.29.41.png
        ├── 4_iphone6Plus_4.Simulator\ Screen\ Shot\ -\ iPhone\ 8\ Plus\ -\ 2018-06-01\ at\ 17.29.46.png
        └── 5_iphone6Plus_5.Simulator\ Screen\ Shot\ -\ iPhone\ 8\ Plus\ -\ 2018-06-01\ at\ 17.29.51.png

6 directories, 46 files

二、Fastlane的文件配置

以下配置文件强烈建议默认使用Sublime Text工具打开,Sublime支持Ruby语法,方便注释以及缩进等编辑

cd fastlane
open -a /Applications/Sublime\ Text.app/ Appfile Deliverfile Fastfile

1、配置.env

用于把账号信息、更新描述、工程相关信息、证书文件等单独放在一个配置文件,方便集中更改。
我们可以在fastlane下创建一个名为.env 的文件,自定义所需的临时变量,然后Fastlane的三个配置文件(AppfileDeliverfileFastfile)分别从.env文件中通过ENV['xxxx']读取配置信息。
首先创建一个.env文件

yangdeMacBook-Pro:NearChargeCompany yang$ cd fastlane
yangdeMacBook-Pro:fastlane yang$ ls -a
.       ..      Appfile     Deliverfile Fastfile    metadata    screenshots
yangdeMacBook-Pro:fastlane yang$ touch .env
yangdeMacBook-Pro:fastlane yang$ ls -a
.       .env        Deliverfile metadata
..      Appfile     Fastfile    screenshots

.env文件为隐藏文件,可使用如下命令查看:

$ defaults write com.apple.finder AppleShowAllFiles -boolean true;
$ killall Finder

以下是我的环境变量配置:

  #APP唯一标识符
  APP_IDENTIFIER = "com.xxx.xx"

  #苹果开发者账号
  APPLE_ID = "xx@xxx.com"
  
  #ADC Team ID
  TEAM_ID = "CN*****SEU"

  #ITC Team ID
  ITC_TEAM_ID = "11*****89"

  #设置shell的语言环境
  LANG = "en_US.UTF-8"
  LC_ALL = "en_US.UTF-8"

  #工程名称
  SCHEME_NAME = "YourProjectName"

  #App 元数据及截图存放路径
  METADATA_PATH = "./metadata"
  SCREENSHOTS_PATH = "./screenshots"

  #ipa输出文件夹路径
  OUTPUT_DIRECTORY = "/Users/xx/Desktop/xxx/ipa"

  #App 元数据及截图下载时 直接覆盖 不询问
  DELIER_FORCE_OVERWRITE= true

  #更新描述
  UPDATE_DESCRIPTION = "fastlane自动打包上传测试"

  #自动提交审核
  SUBMIT_FOR_REVIEW = false

  #审核通过后立刻发布
  AUTOMATIC_RELEASE = false

  #PP文件
  PP_ADHOC = "xxxxxx_ADHoc"
  PP_APPSTORE = "xxxxxx_Distribution"

*注:ADC为开发者网站,ITC是ItunesConnect网站
关于ENV用法可以参考Environment Variables Doc

2、配置Appfile

Appfile文件用于指定 app_identifier, apple_id, team_id, itc_team_id等一些fastlane需要用到的信息.

app_identifier ENV['APP_IDENTIFIER'] # The bundle identifier of your app
apple_id ENV['APPLE_ID'] # Your Apple email address

itc_team_id ENV['ITC_TEAM_ID'] # App Store Connect Team ID
team_id ENV['TEAM_ID'] # Developer Portal Team ID

# For more information about the Appfile, see:
#     https://docs.fastlane.tools/advanced/#appfile

*注:以上文件用到的数据均为从ENV环境变量中取得
Appfile的详细用法可以参考Appfile Doc

3、配置Deliverfile

用于配置应用在 ITC 中的元数据信息,优先级高于编辑metadata文件夹下的文件。

# The Deliverfile allows you to store various App Store Connect metadata
# For more information, check out the docs
# https://docs.fastlane.tools/actions/deliver/


############################# 基本信息 ####################################

# bundle identifier
app_identifier ENV['APP_IDENTIFIER']

# Apple ID用户名
username ENV['APPLE_ID']

# 版权声明
# copyright "2019 xxx Inc"

# 支持语言
supportedLanguages = {
  "cmn-Hans" => "zh-Hans"
}

# app 名称
# name({
# 'zh-Hans' => "APPDemo"
# })

# 副标题
# subtitle(
#   'zh-Hans' => "小鱼小鱼,虾米虾米"
# )

# App价格
#price_tier 0

# 应用程序图标的路径 1024*1024
app_icon './fastlane/metadata/app_icon.jpg'

# 屏幕截图的文件夹的路径
screenshots_path ENV['SCREENSHOTS_PATH']

# 元数据的路径
metadata_path ENV['METADATA_PATH']


###################################  类别配置 ###################################

# 参考网站https://docs.fastlane.tools/actions/upload_to_app_store/#reference
# 设置 App 的类别.这里可以设置一个主要类别,一个次要类别.

# 主要类别 
primary_category "MZGenre.Lifestyle"
# 主要类别第一个子类别 无
# primary_first_sub_category
# 主要类别第二个子类别 无
# primary_second_sub_category

# 要设置的次要类别
secondary_category "MZGenre.Utilities"
# 设置的次要第一个子类别 无
# secondary_first_sub_category  
# 设置的次要第二个子类别 无
# secondary_second_sub_category


################################## 关键字\描述等信息 ###################################

# 搜索关键字
# keywords(
#  "zh-Hans" => "FastLane, 美女"
# )

# 技术支持网址
# support_url({
#  'zh-Hans' => "http://www.baidu.com"
# })

# 营销网址
#marketing_url({ 
#  'zh-Hans' => "http://www.baidu.com"
#})

# 隐私政策网址
#privacy_url({
#  'zh-Hans' => "http://www.baidu.com"
#})

# 本地化宣传文本信息介绍
#promotional_text( 
#  "zh-Hans" => "本地化宣传文本信息介绍",
#)

# app描述信息
#description({ 
#  'zh-Hans' => "APP的描述信息,用于APP功能的描述和介绍不能少于10个字符"
#})

# 版本描述
#release_notes({
#  'zh-Hans' => "这是第一个版本哦"
#})


################################## 分级 ########################################

#年龄分级配置
#app_rating_config_path "./fastlane/metadata/itunes_rating_config.json" 


################################# 提交审核信息等 #########################################

# 提交审核信息:加密, idfa 等
submission_information({    
    export_compliance_encryption_updated: false,
    export_compliance_uses_encryption: false,
    content_rights_contains_third_party_content: false,
    add_id_info_uses_idfa: false
})

# # 应用审核小组的联系信息 app 审核信息
# app_review_information(
#   first_name: "name",
#   last_name: "name",
#   phone_number: "手机号",
#   email_address: "email",
#   demo_user: "测试账号用户名",
#   demo_password: "测试账号密码",
#   notes: "noting"
# )

# run_precheck_before_submit true

# 在上传新截图之前,先清除所有之前上传的截图
overwrite_screenshots true

# 下载 metadata 及 screenshots 时直接覆盖,不询问
force true

# 不上传截图
skip_screenshots true

# 是否自动提交审核,true表示立马提交审核
submit_for_review ENV['SUBMIT_FOR_REVIEW']

# 审核通过后是否立刻发布,false表示需要手动发布
automatic_release ENV['AUTOMATIC_RELEASE']

Deliverfile的详细配置可以参考Deliver Doc

4、配置Fastfile

fastlane 中的块和lane

前面都是小打小闹,接下来就要进入到Fastlane的核心部分了。我们打包、发布等操作都是通过这个文件来执行。

Fastfile里面包含的块类型有以下几种:

desc "打包上传到AppStore"   //该任务的描述
lane :to_appStore do | options |  //定义名字为 to_appStore 的任务,option用于接收我们的外部参数,这里可以传入参数
    customLane  //自定义的lane
    gym(workspace: "expample.xcworkspace", scheme: "example")  //构建App
    deliver  //上传到appstore
end

在控制台进入项目所在的文件夹下面,执行以下命令即可执行任务:

fastlane to_appStore

我们通俗的把一个lane理解为一个任务,每个任务都负责一个功能。 然后我们调用不同的任务,来实现打包、上传到testFlight、上传到app store等功能。 每个任务里可以调用其他的小任务,可以理解为函数,gym、deliver这些Action则是已经给我们封装好的函数。

fastlane 常用的工具集

工具 描述
scan 自动运行测试工具,并且可以生成漂亮的HTML报告
cert 自动创建和管理iOS签名证书(Certificates)
sigh 创建、更新、下载、修复Provisioning Profiles的工具
pem 自动生成、更新推送配置文件
match 一个新的自动创建和管理iOS签名证书和Provisioning Profiles工具(推荐团队使用) 🌟
snapshot Xcode7推出的UI test功能实现自动化截图
frameit 给截屏套上一层外边框
gym 编译打包生成ipa文件,又名build_ios_appbuild_app
produce 如果你的产品还没在iTunes Connect(iTC)或者Apple Developer Center(ADC)建立,produce可以自动帮你完成这些工作
deliver 自动上传截图,APP的元数据,二进制(ipa)文件到iTunes Connect
WatchBuild 一个独立的iTC监控工具,开启WatchBuild可以监控iTC上的文件状态,弹出MacOS自带的Notification

更多工具集的使用可以参考fastlane actions Doc

恭喜你骚年,到目前为止,你已经掌握了fastlane基本的用法,能够完成基本的发包等操作了。接下来就是要讲到插件、自动截图(基于UI Test)以及证书的管理等进阶用法了。

由于fastlane是由Ruby写的,如果想自己实现更多骚操作,可以参考Ruby语法教程。
更多关于Fastfile用法可以参考Fastfile Doc

三、Fastlane插件管理

Fastlane的插件是一个或者一组action的打包,单独发布在fastlane之外。

查找插件

使用fastlane search_plugins查找所有插件,使用fastlane search_plugins [query]查找指定插件

$ fastlane search_plugins pgyer
...
+----------------+----------------------+-----------+
|             fastlane plugins 'pgyer'              |
+----------------+----------------------+-----------+
| Name           | Description          | Downloads |
+----------------+----------------------+-----------+
| pgyer          | distribute app to    | 18497     |
|                | pgyer beta testing   |           |
|                | service              |           |
| pgyer-password | distribute app to    | 1065      |
|                | pgyer beta testing   |           |
|                | service              |           |
| ding_talk      | Auto send the pgyer  | 659       |
|                | app qr code to the   |           |
|                | ding talk.           |           |
+----------------+----------------------+-----------+

安装插件

使用fastlane add_plugin [name]安装插件
下面会用到的两个插件:

$fastlane add_plugin pgyer
[10:46:46]: Get started using a Gemfile for fastlane https://docs.fastlane.tools/getting-started/ios/setup/#use-a-gemfile
[10:46:47]: Plugin 'fastlane-plugin-pgyer' was added to './fastlane/Pluginfile'
[10:46:47]: It looks like fastlane plugins are not yet set up for this project.
[10:46:47]: fastlane will modify your existing Gemfile at path '../Gemfile'
[10:46:47]: This change is necessary for fastlane plugins to work
[10:46:47]: Should fastlane modify the Gemfile at path
'../Gemfile' for you?
(y/n)
y
[10:46:56]: Successfully modified '../Gemfile'
[10:46:56]: Make sure to commit your Gemfile, Gemfile.lock and Pluginfile to version control
Installing plugin dependencies...
Successfully installed plugins

安装成功后在fastlane目录下会多出一个.Pluginfile文件

# Autogenerated by fastlane
#
# Ensure this file is checked in to source control!

gem 'fastlane-plugin-pgyer'
gem 'fastlane-plugin-versioning' //删除这一行就是删除了此插件

*附:上传蒲公英需要去蒲公英的账户设置里获取到API信息

插件使用方法

使用fastlane action查找某个action的使用方法和参数

$ fastlane action pgyer
Loading documentation for pgyer:
+------------------+------------------+------------------+---------+
|                          pgyer Options                           |
+------------------+------------------+------------------+---------+
| Key              | Description      | Env Var          | Default |
+------------------+------------------+------------------+---------+
| api_key          | api_key in your  | PGYER_API_KEY    |         |
|                  | pgyer account    |                  |         |
| user_key         | user_key in      | PGYER_USER_KEY   |         |
|                  | your pgyer       |                  |         |
|                  | account          |                  |         |
| apk              | Path to your     | PGYER_APK        |         |
|                  | APK file         |                  |         |
| ipa              | Path to your     | PGYER_IPA        |         |
|                  | IPA file.        |                  |         |
|                  | Optional if you  |                  |         |
|                  | use the _gym_    |                  |         |
|                  | or _xcodebuild_  |                  |         |
|                  | action. For Mac  |                  |         |
|                  | zip the .app.    |                  |         |
|                  | For Android      |                  |         |
|                  | provide path to  |                  |         |
|                  | .apk file        |                  |         |
| password         | set password to  | PGYER_PASSWORD   |         |
|                  | protect app      |                  |         |
| update_descript  | set update       | PGYER_UPDATE_DE  |         |
| ion              | description for  | SCRIPTION        |         |
|                  | app              |                  |         |
| install_type     | set install      | PGYER_INSTALL_T  |         |
|                  | type for app     | YPE              |         |
|                  | (1=public,       |                  |         |
|                  | 2=password,      |                  |         |
|                  | 3=invite).       |                  |         |
|                  | Please set as a  |                  |         |
|                  | string           |                  |         |
+------------------+------------------+------------------+---------+
* = default value is dependent on the user's system

More information can be found on https://docs.fastlane.tools/actions/pgyer

更多插件的使用可以参考Plugins Doc

四、实战环节


上面说了那么多,是时候展现真正的技术了少年。以下是我的一份自动打包的文件,其中有相关action的相关注释。
如果在提交过程中遇到两步验证,请参考两步验证处理方法
# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane

default_platform(:ios)

# 定义全局参数 大写开头为常数,小写、_开头为变量,$开头为全局变量(直接用#访问)
# scheme名
SCHEME_NAME = ENV['SCHEME_NAME']

# workspace名
WORKSPACE_NAME = "#{SCHEME_NAME}.xcworkspace"

# Bundle ID
APP_IDENTIFIER = ENV['APP_IDENTIFIER']

# app名
APP_NAME = 'FastLaneDemo'

# plist文件路径
INFO_PLIST_PATH = "#{SCHEME_NAME}/Info.plist"

# 版本号
$VERSION_NUMBER = ""

# 构建版本号
$BUILD_NUMBER = ""

# ipa导出路径
$OUTPUT_DIRECTORY = ENV['OUTPUT_DIRECTORY']

# ipa安装包路径
$IPA_PATH = ""

# 是否准备完成
$PREPARE_COMPLETED = false

# 蒲公英 api_key user_key
PGYER_API_KEY = 'xxxxxxx'
PGYER_USER_KEY = 'xxxxxxx'
  
platform :ios do
  before_all do
    # ENV["SLACK_URL"] = "https://hooks.slack.com/services/..."
    # 拉取远程最新代码
    # git_pull
    # 执行 pod instasll
    # cocoapods
    # carthage
  end

  desc '打包前的准备工作'
  lane :prepare do |options|
    if !$PREPARE_COMPLETED
      puts "\033[32m====================即将开始打包====================\033[0m\n"
      puts '您好,我是智能机器人邓逼逼,即将为你自动打包'
    end

    export_method = options[:export_method]
    select_method = '-1'
    # => 如果没有选择打包方式,提示选择打包方式
    if export_method.nil? || export_method.empty?
      puts "请选择打包方式 \033[33m1:上传appstore(默认)  2:打包adHoc上传蒲公英  3:打包Inhouse上传蒲公英  0:结束打包  回车表示使用默认打包\033[0m"
      select_method = STDIN.gets.chomp
      if select_method!='1' && select_method!='2' && select_method!='3' && !select_method.empty?
        # supported [:select, :message, :verbose, :error, :password, :input, :success, :important, :command, :user_error!, :command_output, :deprecated, :header, :content_error, :interactive?, :confirm, :crash!, :not_implemented, :shell_error!, :build_failure!, :test_failure!, :abort_with_message!]
          UI.user_error!("您已取消打包 🚀")
      end
    end

    if !$PREPARE_COMPLETED
      currentVersion = get_info_plist_value(path: "#{INFO_PLIST_PATH}", key: "CFBundleShortVersionString")
      currentBuild = get_info_plist_value(path: "#{INFO_PLIST_PATH}", key: "CFBundleVersion")
      puts "当前工程的版本号是:\033[33m#{currentVersion}\033[0m 构建版本号是:\033[33m#{currentBuild}\033[0m"
      version = options[:version]
      build = options[:build]
      output_directory = options[:output_directory]
      
      # => 如果没有选择版本号,提示是否需要输入版本号
      if version.nil? || version.empty?
        puts "请输入版本号,回车表示使用当前版本号\033[33m#{currentVersion}\033[0m"
        version = STDIN.gets.chomp
        if version == '' # 回车
          $VERSION_NUMBER = currentVersion
        else
          $VERSION_NUMBER = version
        end
      else
        $VERSION_NUMBER = version
      end
      # => 如果没有选择构建版本号,提示是否需要输入构建版本号
      if build.nil? || build.empty?
        puts "请输入构建版本号,回车表示使用默认自动生成构建版本号"
        build = STDIN.gets.chomp
        if build == '' # 回车
          # $BUILD_NUMBER = AUTO_BUILD_NUMBER
        else
          $BUILD_NUMBER = build
        end
      else
        $BUILD_NUMBER = build
      end
      # => 如果没有选择ipa输出目录,提示是否需要输入打包路径
      if output_directory.nil? || output_directory.empty?
        puts "请指定ipa包输出路径,回车表示使用默认输出路径:\033[33m#$OUTPUT_DIRECTORY\033[0m"
        output_directory = STDIN.gets.chomp
        if output_directory == '' # 回车
        else
          $OUTPUT_DIRECTORY = output_directory
        end
      else
        $OUTPUT_DIRECTORY = output_directory
      end
    end
    
    $PREPARE_COMPLETED = true

    if select_method != '-1' # 已选择
      case select_method
      when '1',''
        # 发布到appstore
        release_appstore(options)
      when '2'
        puts "发布到蒲公英"
        # 打包adhoc发布到蒲公英
        release_adhoc(options)
      when '3'
        # 打包inhouse发布到蒲公英
        
      end
      next
    end
    
    # => 详细信息
    summary(options)

  end

  desc "信息确认"
  lane :summary do |options|
    puts "\033[32m====================信息确认====================\033[0m\n"
    puts "您设置的包输出路径为:"
    # supported [:select, :message, :verbose, :error, :password, :input, :success, :important, :command, :user_error!, :command_output, :deprecated, :header, :content_error, :interactive?, :confirm, :crash!, :not_implemented, :shell_error!, :build_failure!, :test_failure!, :abort_with_message!]
    UI.important "#$OUTPUT_DIRECTORY"
    puts "您选择的打包方式为:"
    UI.important "#{options[:export_method]}"
    puts "指定的发布版本号为:"
    UI.important "#$VERSION_NUMBER"
    confirm = UI.confirm "确认信息是否正确,输入y继续打包"
    if !confirm
      UI.user_error!("您已取消打包 🚀")
    end
    puts "\033[32m====================信息确认====================\033[0m\n"
    puts "3s后开始自动打包..."
    sleep(3)
  end

  desc "更新版本号"
  lane :update_version do
    puts("*************| 更新version #$VERSION_NUMBER |*************")
    increment_version_number_in_plist(
      target: SCHEME_NAME,
      version_number: $VERSION_NUMBER
    )
    puts("*************| 更新build #$BUILD_NUMBER |*************")
    increment_build_number_in_plist(
       target: SCHEME_NAME,
       build_number: $BUILD_NUMBER
    )
  end

  desc "打包发布"
  lane :release do |options|
    prepare(options)
  end

  desc "发布到appstore"
  lane :release_appstore do |options|
    options[:export_method] = "app-store"
    prepare(options)
    build(options)
    deliver_appstore
  end

  desc "发布ad-hoc"
  lane :release_adhoc do |options|
    options[:export_method] = "ad-hoc"
    prepare(options)
    build(options)
    deliver_pgyer
  end

  desc "发布企业Inhouse"
  lane :release_enterprise do |options|
    options[:export_method] = "enterprise"
    prepare(options)
    build(options)
  end

  desc "上传到蒲公英"
  lane :deliver_pgyer do |options|
    pgyer( 
       api_key: PGYER_API_KEY, # 从蒲公英项目详情中获取的apikey
       user_key: PGYER_USER_KEY, # 从蒲公英项目详情中获取的 userkey
       ipa: $IPA_PATH, #ipa包路径
       #password: "123456", #设置安装密码
       #install_type: "2", #1:公开,2:密码安装,3:邀请安装,4:回答问题安装。默认为1公开
       update_description: ENV['UPDATE_DESCRIPTION']
    )
  end
  
desc "上传到appstore"
  lane :deliver_appstore do |options|
    deliver( 
       username: ENV['APPLE_ID'], # 开发者账号
       team_id: ENV['ITC_TEAM_ID'], # ITC Team ID
       dev_portal_team_id: ENV['TEAM_ID'], # ADC Team ID
       app_identifier: ENV['APP_IDENTIFIER'], # bundle ID
       ipa: $IPA_PATH, # ipa包路径
       app_version: $VERSION_NUMBER, # 更新版本号
       release_notes: {
         'zh-Hans' => "这是第一个版本哦"
       },
       force: true, # 设置true,会跳过预览页面,直接上架
       skip_screenshots: true, # 不上传截图
       skip_metadata: true, # 不上传元数据
    )
  end

  desc "打包"
  lane :build do |options|
    # gym用来编译ipa
    # 编译时间
    build_time = Time.now.strftime("%Y-%m-%d %H-%M-%S")
    # 自动生成的build版本号
    auto_build_number = Time.now.strftime("%Y%m%d%H%M%S")
    if $BUILD_NUMBER.empty?
      $BUILD_NUMBER = auto_build_number
    end

    # 更新版本号
    update_version

    # 获取打包方式
    export_method = options[:export_method]
    # 配置项
    configuration = 'Release'
    # pp文件
    provisioningProfiles = ENV['PP_APPSTORE']
    # 输出目录
    outputDir = ''
    # 输出文件名
    outputName = "#{SCHEME_NAME}_#$VERSION_NUMBER_#$BUILD_NUMBER_#{export_method}.ipa"
    case export_method
    when 'development'
      configuration = 'Debug'
      outputDir = "#$OUTPUT_DIRECTORY/Development/#{SCHEME_NAME}-#{build_time}"
    when 'app-store'
      outputDir = "#$OUTPUT_DIRECTORY/Appstore/#{SCHEME_NAME}-#{build_time}"
    when 'ad-hoc'
       provisioningProfiles = ENV['PP_ADHOC']
       outputDir = "#$OUTPUT_DIRECTORY/Pgyer/#{SCHEME_NAME}-#{build_time}"
    when 'enterprise'
       provisioningProfiles = ENV['PP_ENTERPRISE']
       outputDir = "#$OUTPUT_DIRECTORY/Pgyer/#{SCHEME_NAME}-#{build_time}"
    end
   
    $IPA_PATH = gym(
       clean: 'true', # 在打包前是否先执行clean。
       scheme: "#{SCHEME_NAME}", # 指定项目的scheme名称
       workspace: "#{WORKSPACE_NAME}", # 指定.xcworkspace文件的路径。
       configuration: "#{configuration}", # 指定打包时的配置项,默认为Release
       output_name: "#{outputName}", # 指定生成的.ipa文件的名称,应包含文件扩展名。
       output_directory: "#{outputDir}", # 指定.ipa文件的输出目录
       include_symbols: 'true', # 是否导出符号表
       # include_bitcode: 'false',  # 是否使用bitcode打包
       export_xcargs: "-allowProvisioningUpdates", #访问钥匙串
       silent: true,  # 是否隐藏打包时不需要的信息。
       buildlog_path: "#{outputDir}", # 指定编译日志文件的输出目录
       export_options: {
        method: "#{export_method}", # 指定导出.ipa时使用的方法,可用选项:app-store,ad-hoc,enterprise,development
        thinning: "<none>",  # 是否瘦身
        provisioningProfiles: {  # 指定pp文件
          "#{APP_IDENTIFIER}" => "#{provisioningProfiles}"
        },
        signingStyle: "manual" # 手动签名
       }
    )
  end

  desc "新创建一个app"
  lane :create_app do
​    produce(
        username: 'test@qq.com',
        app_identifier: 'com.company.TestProject',
        app_name: '测试工程',
        language: 'Simplified Chinese',
        app_version: '1.0',
        sku: '123', # 注意,sku必须大于2个字符
        team_name: 'DNxxxx', # only necessary when in multiple teams
        #如果只在AppleDeveloper创建app,不在iTunesConnect创建app的话
        #skip_itc: true,

        # Optional
        # App services can be enabled during app creation
        enable_services: {
          # access_wifi: "on",             # Valid values: "on", "off"
          # app_group: "on",               # Valid values: "on", "off"
          # apple_pay: "on",               # Valid values: "on", "off"
          # associated_domains: "on",      # Valid values: "on", "off"
          # auto_fill_credential: "on",    # Valid values: "on", "off"
          # data_protection: "complete",   # Valid values: "complete", "unlessopen", "untilfirstauth",
          # game_center: "on",             # Valid values: "on", "off"
          # health_kit: "on",              # Valid values: "on", "off"
          # home_kit: "on",                # Valid values: "on", "off"
          # hotspot: "on",                 # Valid values: "on", "off"
          # icloud: "cloudkit",            # Valid values: "legacy", "cloudkit"
          # in_app_purchase: "on",         # Valid values: "on", "off"
          # inter_app_audio: "on",         # Valid values: "on", "off"
          # passbook: "on",                # Valid values: "on", "off"
          # multipath: "on",               # Valid values: "on", "off"
          # network_extension: "on",       # Valid values: "on", "off"
          # nfc_tag_reading: "on",         # Valid values: "on", "off"
          # personal_vpn: "on",            # Valid values: "on", "off"
          # passbook: "on",                # Valid values: "on", "off" (deprecated)
          # siri_kit: "on",                # Valid values: "on", "off"
          # vpn_configuration: "on",       # Valid values: "on", "off" (deprecated)
          # wallet: "on",                  # Valid values: "on", "off"
          # wireless_accessory: "on",      # Valid values: "on", "off"
          push_notification: "on",       # Valid values: "on", "off"
        }
    )
  end

  after_all do |lane|
    #slack(
    #   message: "Successfully deployed new App Update."
    #)
  end

  error do |lane, exception|
     #slack(
     #  message: exception.message,
     #  success: false
     #)
  end

end

配置好Fastfile后cd到工程目录下,调用fastlane release实现自动打包。

Couldn't find specified scheme 'YourScheme'. Please make sure that the scheme is shared, see ...

如果发现出现上面的错误,请勾选scheme的Shared。


未完待续

本篇只是简单的写了关于Fastlane的安装配置以及自动打包发布的流程,由于篇幅有限,很多其他的功能未能详细说明,后续我会补上自动截图、证书管理、钉钉通知以及上传dSYM到Bugly等功能。


后续文章更新啦~
iOS开发fastlane从入门到入土(二):自动截屏
iOS开发fastlane从入门到入土(三):证书管理
上一篇下一篇

猜你喜欢

热点阅读