LoginSignup
3
2

【iOS】Sign in with apple 初回以降のサインインでユーザー情報を取得できない

Last updated at Posted at 2023-12-02

状況

SwiftUIにて、Signin with Appleのトライしていたところ、初回サインインではユーザー名やemailを取得できたのですが、それ以降のサインイン後はnilが返ってくるという現象が起きました。調べた結果を備忘録として書いておきます。

試したコード

こんなコードで試しました。

AuthScreen.swift
struct AuthScreen: View {
    @State var givenName: String?
    @State var familyName: String?
    @State var email: String?
    
    var body: some View {
        VStack {
            Text("givenName: \(givenName ?? "is nil")")
            Text("familyName: \(familyName ?? "is nil")")
            Text("email: \(email ?? "is nil")")

            SignInWithAppleButton(.signIn) { request in
                    request.requestedScopes = [.fullName, .email]
                } onCompletion: { authResults in
                    switch authResults {
                    case .success(let authResults):
                        guard let appleIDCredential = authResults.credential as? ASAuthorizationAppleIDCredential
                            else { return }
                        if let fullName = appleIDCredential.fullName { 
                            self.givenName = fullName.givenName
                            self.familyName = fullName.familyName
                        }
                        self.email = appleIDCredential.email
                    case .failure(let error):
                        print(error.localizedDescription)
                    }
                }
            .signInWithAppleButtonStyle(.black)
            .padding(.horizontal, 16)
        }
    }
}

初回サインイン後はこのようにgivenName familyName emailが取得できます。
image.png

その後サインアウト状態から再度サインインするとgivenName familyName emailがnilで返ってきてしまいます。

原因

同じ現象についてのフォーラムを見つけました。

ユーザ情報は最初のユーザ登録時にのみ ASAuthorizationAppleIDCredential に送信されます。その後、同じアカウントでSign In with Appleを使用してアプリにログインしても、ユーザ情報は共有されず、ASAuthorizationAppleIDCredentialにユーザ識別子が返されるだけです。アカウントがサーバに正常に作成されたことを確認できるまで、ユーザ情報を含む最初のASAuthorizationAppleIDCredentialを安全にキャッシュすることをお勧めします。

要は、ASAuthorizationAppleIDCredentialからgivenName familyName emailが返されるのは最初のサインアップの時のみです。

必要な情報は、初回にきちんとセキュアに(サーバーサイドに)キャッシュしておこうね、ということですね。

じゃあサインアップ履歴を削除したい

ユーザー情報のキャッシュが未実装だけどとりあえずユーザー情報を確認したい、という場合は以下の手順でサインアップ履歴を削除してリセットできます。

(1)ここにログインします
https://appleid.apple.com/account/manage

(2)「サインインとセキュリティ」を開きます
image.png

(3)「Appleでサインイン」を開きます
image.png

(4)該当のアプリを選択し、「Appleでサインインの使用を停止」を押します
image.png

これで次のサインインが初回扱いになり、ユーザー情報を取得できます。

おわりに

Signin with Appleは必須の技術なので、目瞑ってても実装できるようになりたい

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2