作為一名 Flutter 開發者,通常會在開發過程中遇到這樣一個問題:沒有蘋果開發者賬號,如何將自己的應用打包並安裝到 iOS 設備上進行測試呢?別擔心,今天我們就來詳細探討一下這個過程。

真機調試

準備 Apple ID

首先,你需要一個 Apple ID。如果沒有,可以前往蘋果官網註冊一個,註冊過程比較簡單。註冊成功後,登錄蘋果開發者中心,同意相關協議即可。

配置 Xcode

打開 Xcode,依次點擊 Settings → Account,點擊 + 號,選擇 Apple ID 添加剛才註冊的賬號。添加成功後,雙擊 Team 處的選項,點擊 + → Apple Development,生成蘋果開發證書,然後點擊 Done。

打開項目

在終端中,使用 git clone 命令將你的 Flutter 項目克隆到本地。進入項目目錄,如果項目中使用了需要運行時代碼生成的庫,執行相應的代碼生成命令。然後雙擊打開 ios 目錄下的 Runner.xcworkspace 文件,使用 Xcode 打開項目。

處理可能遇到的報錯

在構建項目時,可能會遇到一些報錯。例如:

  • could not find inclued file 'Generated.xcconfig' :執行 flutter build ios 命令,忽略該報錯,後續配置開發者證書後再進行處理。
  • Module 'xxx' not found :執行 cd iosflutter cleanflutter pub getpod install 命令。如果仍然報錯,檢查 Podfile 文件中的 platform 版本,修改後重新執行相關命令。如果還是不行,可能需要卸載重裝 cocoapods。

手機調試設置

將手機連接到電腦,點擊彈窗中的 “信任” 按鈕。在 Xcode 中,點擊 Runner 選中 “Signing & Capabilities”,在 Team 處選擇剛才添加的賬號。點擊運行按鈕,如果失敗,按照提示在手機的 “設置 → 隱私和安全 → 打開開發者模式”。開啓後,再次點擊運行按鈕,手機會出現彈窗,點擊 “設置 → 通用 → VPN 與設備管理”,找到我們的 App,點擊 “信任”。此時,App 就成功運行到手機上了。

為了方便調試,可以將構建模式修改為 Release。依次點擊 Runner → Edit Scheme... → Info 選項,將 Build Configuration 切換為 Release。這樣,拔線後 App 也不會閃退。

此外,還可以設置無線調試。手機要先插着且與電腦處於同一個 Wifi 網絡。點擊 Xcode 頂部菜單的 Windows → Device and Simulators,在 Device 中找到真機,勾選 Connect via network。真機設備右邊出現小地球標誌,説明配置成功,此時拔線也能正常運行 App。

將應用安裝到其他手機上

生成 ipa 包

Flutter 提供了 flutter build ipa 命令來生成 ipa 包,但使用白嫖的 Apple ID 會報錯。可以使用以下腳本將 .app 文件轉換為 ipa 包:

#!/bin/bash

# Ensure a file was dragged onto the script
if [ -z "$1" ]
then
    echo "No file provided. Please drag and drop the .app file onto this script."
    exit 1
fi

# Extract the app name from the file path
appName=$(basename "$1" .app)

# Remove any existing directory with the same name
rm -rf "$appName"

# Create necessary directories
mkdir "$appName"
mkdir "$appName/Payload"

# Copy the .app file into the Payload directory
cp -r "$1" "$appName/Payload/$appName.app"

# If there's an icon file, copy it over
if [ -f Icon.png ]
then
    cp Icon.png "$appName/iTunesArtwork"
fi

# Change to the app directory
cd "$appName"

# Create the .ipa file
zip -r "$appName.ipa" Payload iTunesArtwork

# Print the absolute path of the .ipa file
echo "The .ipa file has been created at: $(pwd)/$appName.ipa"

# Exit successfully
exit 0

將腳本保存為 app_to_ipa.sh 後,給腳本執行權限,然後運行腳本,即可得到 ipa 文件路徑。

PC 上自簽名

生成的 ipa 文件需要進行簽名才能安裝到其他手機上。可以使用愛思助手進行 Apple ID 自籤 IPA。打開愛思助手,依次點擊工具箱 → IPA 簽名 → 使用 Apple ID 簽名,添加 Apple ID 後,對 ipa 文件進行簽名。需要注意的是,使用 Apple ID 簽名的方式,程序運行時間通常只能維持 7 天左右,到期後需要重新簽名和安裝。