質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Authentication

Authentication(認証)は正当性を認証する為の工程です。ログイン処理等で使われます。

Q&A

解決済

1回答

2267閲覧

apple認証で2回目以降のアプリ起動時の動きについて

po_tato

総合スコア97

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Authentication

Authentication(認証)は正当性を認証する為の工程です。ログイン処理等で使われます。

0グッド

0クリップ

投稿2020/07/02 07:47

ページ下部添付の記事を参考に
作成中のアプリにApple認証を実装してるのですが、
初回起動時のApple認証の一連の流れは無事動作しました。

問題は、2回目以降の起動ですが、
アプリを起動するたびに認証の工程が表示されるのはユーザー側からしたらとても面倒なので、
サインイン状況を取得できるASAuthorizationAppleIDProvider().getCredentialState(forUserID: )
を使用して2回目以降はLoginViewControllerをスキップしてアプリのメイン画面を起動したいのですが、
なぜか、結果がcase .notFound:になってしまいうまくいきません。

なぜ、一度サインインしているのにcase .authorized:ではなく、このような結果になってしまうのでしょうか?
ご教示頂けますと幸いでございます。

AppDelegate

import UIKit import NCMB import AuthenticationServices @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // APIキー let applicationKey = "~~~" let clientKey = "~~~" // APIキーの設定とSDK初期化 NCMB.initialize(applicationKey: applicationKey, clientKey: clientKey); // on the initial view controller or somewhere else, check the userdefaults if let userID = UserDefaults.standard.string(forKey: "userID") { // move to main view print("以前にログイン済み") print(userID) // get the login status of Apple sign in for the app // asynchronous ASAuthorizationAppleIDProvider().getCredentialState(forUserID: userID, completion: { credentialState, error in switch(credentialState){ case .authorized: print("user remain logged in, proceed to another view") //self.performSegue(withIdentifier: "LoginToUserSegue", sender: nil) case .revoked: print("user logged in before but revoked") case .notFound: print("user haven't log in before") default: print("unknown state") } }) }else{ goLoginViewConroller() } return true } //ログインコントローラーに遷移 func goLoginViewConroller(){ //画面遷移させたい部分に以下の処理を記述 // windowを生成 self.window = UIWindow(frame: UIScreen.main.bounds) // Storyboardを指定 let storyboard = UIStoryboard(name: "Main", bundle: nil) // Viewcontrollerを指定 let loginViewController = storyboard.instantiateViewController(withIdentifier:"login") // rootViewControllerに入れる self.window?.rootViewController = loginViewController // 表示 self.window?.makeKeyAndVisible() } }

LoginViewController

import UIKit import AuthenticationServices import NCMB class LoginViewController: UIViewController,ASAuthorizationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() //「Sign in with Apple」ボタン作成 let siwaButton = ASAuthorizationAppleIDButton() // set this so the button will use auto layout constraint siwaButton.translatesAutoresizingMaskIntoConstraints = false // add the button to the view controller root view self.view.addSubview(siwaButton) // set constraint NSLayoutConstraint.activate([ siwaButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 50.0), siwaButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -50.0), siwaButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -70.0), siwaButton.heightAnchor.constraint(equalToConstant: 50.0) ]) // the function that will be executed when user tap the button siwaButton.addTarget(self, action: #selector(appleSignInTapped), for: .touchUpInside) } // 「Sign in with Apple」ボタンがタップされたときの処理 @objc func appleSignInTapped() { // Apple IDによる認可のリクエスト let appleIDProvider = ASAuthorizationAppleIDProvider() let request = appleIDProvider.createRequest() request.requestedScopes = [.fullName, .email] let authorizationController = ASAuthorizationController(authorizationRequests: [request]) authorizationController.delegate = self as? ASAuthorizationControllerDelegate authorizationController.presentationContextProvider = self as? ASAuthorizationControllerPresentationContextProviding authorizationController.performRequests() } // 認証処理に成功した時のコールバック func authorizationController(controller _: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) { switch authorization.credential { case let appleIDCredential as ASAuthorizationAppleIDCredential: print("AppleID > 認証完了") // mobile backend に会員登録・認証を行う準備します let authorizationCode = String(data: appleIDCredential.authorizationCode!, encoding: String.Encoding.utf8) ?? "Data could not be printed" //NCMBAppleParametersで発行された認証情報を指定します let appleParam = NCMBAppleParameters(id: appleIDCredential.user, accessToken: authorizationCode) // mobile backendに会員登録・認証を行います NCMBUser().signUpWithAppleToken(appleParameters: appleParam, callback: { result in switch result { case .success: print("NCMB > 認証完了") //初回ログイン時にログイン情報をuserDefaultに保持 if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential { let userID = appleIDCredential.user let userFirstName = appleIDCredential.fullName?.givenName let userLastName = appleIDCredential.fullName?.familyName let mailAddress = appleIDCredential.email print("userFirstName(String(describing: userFirstName))") print("userLastName(String(describing: userLastName))") print("mailAddress(String(describing: mailAddress))") UserDefaults.standard.set(userID, forKey: "userID") } DispatchQueue.main.async { //完了したらinitial画面に遷移 let storyboard: UIStoryboard = self.storyboard! let initialViewController = storyboard.instantiateViewController(withIdentifier: "initial") let nav = UINavigationController(rootViewController: initialViewController) nav.modalPresentationStyle = .fullScreen self.present(nav, animated: true, completion: nil) } case let .failure(error): print("NCMB > 認証エラー: (error)") }}) default: break } } }

環境
Xcode: Version 11.3.1 (11C504)
シミュレーター: iPhone11 Pro Version 13.3
実機 : iPhone7 Version 13.3.1

参考記事1
参考記事2

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

po_tato

2020/07/02 08:40

なるほど、シミュレータだとだめなのですね。 実機で確認して最初はうまくいかなかったのですが、 今は希望通りの動作になっております! ありがとうございました!
guest

回答1

0

自己解決

シミュレーターだとうまくいかないみたいでした。

投稿2020/07/02 08:41

po_tato

総合スコア97

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問