在 iOS App 裡實現密碼自動填寫

想像一下這個使用情境,某個服務有 Web 也有 App,若使用者有用 Safari 登入並記住密碼,那麼在 App 裡點擊 Text Field 的鍵盤會提示是否要用已儲存的密碼,點擊後帳號密碼就會填入對應的 Text Field 中,使用者完全不用自行輸入非常方便。

若要實現這功能需要從 App 以及 Web 兩邊都做設定,且系統需求為 iOS 11 以上。

 

Apple Developer 設定

先去 iOS App IDs 確定該 ID 的 Associated Domains 為啟用狀態。

 

Xcode 專案設定

Target → Capabilities → 打開 Associated Domains → + → "webcredentials:example.com"

 

Web 設定

新增一個 apple-app-site-association 檔案(沒有副檔名),內容如下:

{
    "webcredentials": {
        "apps": [
            "D3KQX62K1A.com.example.DemoApp",
            "D3KQX62K1A.com.example.DemoAdminApp"
        ]
    }
}

若已有這個檔案,只要加入 webcredentials 這個層級並保持 JSON 結構即可。
D3KQX62K1A 為 Team ID ,可以從這裡找到。
com.example.DemoApp 為 Bundle Identifier 。

將此檔案放在網站的 .well-known 資料夾下,整個網址就像這樣 https://example.com/.well-known/apple-app-site-association ,需注意必須要 https:// 開頭,如果有子網域也要分別作設定。每當 App 安裝或是更新版本才會去抓 apple-app-site-association 。

 


現在你可以試試先在網站登入並儲存密碼,儲存的密碼可在 設定 → 帳號與密碼 → App 與網站密碼 裡找到。

然後回到 App 的登入畫面裡點擊 Text Field 應該就可使用儲存的帳號密碼了,雖然這只是單向的。

 


你可能會發現並非所有的 Text Field 都會出現,因為預設是以 secureTextEntry 這屬性來判斷是否為密碼,若沒指定則需要另外要用 textContentType 來指定:

userTextField.textContentType = .username
userTextField.keyboardType = .emailAddress
passwordTextField.textContentType = .password

newPasswordTextField.textContentType = .newPassword
confirmPasswordTextField.textContentType = .newPassword

singleFactorCodeTextField.textContentType = .oneTimeCode

 

參考資料
https://developer.apple.com/documentation/security/password_autofill/
https://developer.apple.com/documentation/security/password_autofill/setting_up_an_app_s_associated_domains
https://developer.apple.com/documentation/security/password_autofill/enabling_password_autofill_on_a_text_input_view

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *