Sign In with Appleをアプリに実装したい[iOS13 Xcode11]
この投稿は
WWDC2019も終わり、例年通り時期iOSの発表もありました。
いろいろ気になるものはありましたが、「Sign In with Apple」で会員系のサービスを促進したいなと思って調べてみました。
実装方法
※いわずもがな、まだiOS13はβ版です。今後のアップデートで何かしら変更が入る可能性がありますし、私の理解が誤っている場合もありますので参考までにとどめてくださいね。
準備
AuthenticationServices.frameworkを追加
とりあえず、「Sign In with Apple」的なボタンを適当につくってメソッドと紐づけておく。
以上で準備完了です。あとは実装するだけです!
コーディング
ボタンに紐づいたメソッドでリクエストを実行します
/**
* SignInWithApplenボタン押下
*/
- (IBAction)signIn:(id)sender {
ASAuthorizationAppleIDProvider *provider = [[ASAuthorizationAppleIDProvider alloc] init];
ASAuthorizationAppleIDRequest *request = [provider createRequest];
[request setRequestedScopes:@[ASAuthorizationScopeFullName,ASAuthorizationScopeEmail]];
ASAuthorizationController *controller = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
controller.delegate = self;
[controller performRequests];
}
ASAuthorizeの成功、失敗のデリゲートメソッドを実装
/**
* SignIn成功時
*/
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(nonnull ASAuthorization *)authorization
{
ASAuthorizationAppleIDCredential *appleIDCredential = [authorization credential];
// appleIDCredentialから情報取得(初回のみ?)
NSString *user = [appleIDCredential user];
NSString *email = [appleIDCredential email];
NSString *fullName = [NSString stringWithFormat:@"%@ %@", [[appleIDCredential fullName] familyName], [[appleIDCredential fullName] givenName]];
// 二回目以降はjwt形式でエンコードされている値でのみ返すっぽい
NSData *tokenData = appleIDCredential.identityToken;
NSString *tokenDataString = [[NSString alloc] initWithData:tokenData encoding:NSUTF8StringEncoding];
NSLog(@"user:%@\nemail:%@\nfullName:%@",user, email, fullName);
// ここでサーバーに送るなどログイン処理
}
/**
* SignIn失敗時
*/
- (void) authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error
{
// エラー処理
}
こんな感じですかね。
とりあえず成功時に最低限の処理を書きましたが、エラーハンドリングもベストプラクティスがわかれば追記していきますね。
どうも2回目以降はappleIDCredentialにemailとfullNameが入ってませんでした。
なので、appleIDCredential.identityTokenをデコードして取り出す必要がありそうです。
感想
超簡単。どこぞのめんどくさいOAuthを思い出せばめっちゃ簡単でした。
ぶっちゃけそこまでドキュメントを真面目に読んでいないのでまだまだ色々やるべきことはあると思いますが、必要最低限のデータ取得はこれでできました。
これで会員増えたらいいな。
Author And Source
この問題について(Sign In with Appleをアプリに実装したい[iOS13 Xcode11]), 我々は、より多くの情報をここで見つけました https://qiita.com/GoGoNaoya/items/dab5ed88ebaefd4247da著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .