新型コロナウイルスの影響もあり、6月末までに延長されていますが、ソーシャルログインを利用しているアプリのSign in with Apple対応が迫られています。ニフクラ mobile backendでもFacebook/Twitter/Google認証を提供しており、それらを使っている方も多いかと思います。
先日ニフクラ mobile backendではSign in with Appleに対応しました。今回はSwiftUIを使った実装方法について解説します。
- コードについて
- SDKのインストール
- Capabilityの追加
- AppDelegate.swiftについて
- SignInWithApple.swiftの追加
- ContentView.swiftの編集
- SignInWithAppleDelegates.swiftの追加
- 管理画面での設定
- 注意点
- まとめ
コードについて
基本的な実装を行ったコードを下記に公開しています。
NCMBMania/Sign-in-with-Apple-Swift
SDKのインストール
SDKはCocoaPods経由でインストールしています。
Capabilityの追加
XcodeのCapabilitiesでSign in with Appleを追加します。
AppDelegate.swiftについて
AppDelegate.swiftではNCMBの初期化を行っています。まずNCMBのインポートを追加します。
import NCMB
次に didFinishLaunchingWithOptions で初期化します。
NCMB.initialize(applicationKey: "53e...fff", clientKey: "3ba...bbf")
SignInWithApple.swiftの追加
SwiftUIとしてSignInWithApple.swiftを追加します。これはSign in with Appleのボタンを表示するものです。 ASAuthorizationAppleIDButton
がボタンです。
import SwiftUI import AuthenticationServices final class SignInWithApple: UIViewRepresentable { func makeUIView(context: Context) -> ASAuthorizationAppleIDButton { return ASAuthorizationAppleIDButton() } func updateUIView(_ uiView: ASAuthorizationAppleIDButton, context: Context) { } }
ContentView.swiftの編集
ContentView.swiftではまずボタンを表示します。
var body: some View { SignInWithApple() .frame(width: 280, height: 60) .onTapGesture(perform: showAppleLogin) }
ボタンをタップされた時の動作としてshowAppleLoginを実装します。名前とメールアドレスをリクエストします。
private func showAppleLogin() { let request = ASAuthorizationAppleIDProvider().createRequest() request.requestedScopes = [.fullName, .email] performSignIn(using: [request]) }
performSignInの処理内容は次のようになります。
private func performSignIn(using requests: [ASAuthorizationRequest]) { appleSignInDelegates = SignInWithAppleDelegates(window: window) { success in if success { print("success") } else { print("error") } } let controller = ASAuthorizationController(authorizationRequests: requests) controller.delegate = appleSignInDelegates controller.presentationContextProvider = appleSignInDelegates controller.performRequests() }
SignInWithAppleDelegates.swiftの追加
SwiftUIとしてSignInWithAppleDelegates.swiftを追加します。こちらは認証後の処理を行います。
import UIKit import AuthenticationServices import Contacts import NCMB class SignInWithAppleDelegates: NSObject { private let signInSucceeded: (Bool) -> Void private weak var window: UIWindow! init(window: UIWindow?, onSignedIn: @escaping (Bool) -> Void) { self.window = window self.signInSucceeded = onSignedIn } }
認証処理が完了するとauthorizationControllerが呼ばれます。ここでAppleから送られてきた情報を使ってsignUpWithAppleTokenを実行します。これで会員登録できます。
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) { switch authorization.credential { case let appleIDCredential as ASAuthorizationAppleIDCredential: // 認証情報による認証の場合、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) let user = NCMBUser() if (appleIDCredential.fullName?.familyName != nil && appleIDCredential.fullName?.givenName != nil) { let familyName = appleIDCredential.fullName?.familyName ?? "" let givenName = appleIDCredential.fullName?.givenName ?? "" user["fullName"] = "\(givenName) \(familyName)" } user["email"] = appleIDCredential.email // mobile backendに会員登録・認証を行います user.signUpWithAppleToken(appleParameters: appleParam, callback: { result in switch result { case .success: print("会員認証完了しました。") case let .failure(error): print("エラー: \(error)") }}) break default: break } } }
管理画面での設定
Sign in with Appleを使う際には、管理画面で次の情報を設定します。
- Apple ID連携の許可
許可するに設定 - App ID
アプリのID - AppleチームID
iOS Member Centerで表示されるもの - AppleキーID
iOS Member Centerで作成するもの - 秘密鍵(p8ファイル)
iOS Member CenterでAppleキーIDを作成時にダウンロードできるもの
注意点
会員登録時には名前とメールアドレスが取得できますが、2回目以降は返ってきません。会員登録時に必ず保存するようにしてください。
まとめ
Sign in with Appleの実装はコード量こそ多くはありませんが、SwiftUIがあるプロジェクトもあれば、そうでないものあり、情報がまだ多くありません。実装する必要がある場合には、ぜひ早めのトライしてください。