iOS - SignInWithApple(苹果账号登录)

在 WWDC 2019 上,苹果推出了自家的 Sign in with Apple 功能。iOS13之后,App上如果有如”微信授权登录”的第三方登录,就必须提供“苹果登录”选项。(强制性的呦😄) 苹果官网有介绍 自行翻译

一、初识SignInWithApple登录授权原理
苹果登录授权原理草图.png

二、苹果开发者后台配置

1、配置Identifiers

找到项目对应的id,点击进入编辑页面,选中此项
Identifiers.png
image.png

2、配置项目

Xcode->TARGETS->Signing&Capabilities中添加Sign In With Apple选项
TARGETS配置.png

三、编辑苹果按钮代码

3.0、代码引入 #import "AppDelegate.h"

#import "AppDelegate.h"
#pragma mark - 苹果账号登录
#import <AuthenticationServices/AuthenticationServices.h>

@interface AppDelegate ()

@end

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
#pragma mark- 苹果账号登录配置
    [self observeAuthticationState];
    
    return YES;
}

#pragma mark - Private functions 用户注销 AppleId 或 停止使用 Apple ID 的状态处理
// 观察授权状态
- (void)observeAuthticationState {
    
    if (@available(iOS 13.0, *)) {
        
        // 注意 存储用户标识信息需要使用钥匙串来存储 这里使用NSUserDefaults 做的简单示例
        NSString *userIdentifier = [[NSUserDefaults standardUserDefaults] valueForKey:@"appleID"];
        
        if (userIdentifier) {
            
            ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
            
            [appleIDProvider getCredentialStateForUserID:userIdentifier
                                              completion:^(ASAuthorizationAppleIDProviderCredentialState credentialState, NSError * _Nullable error) {
                switch (credentialState) {
                    case ASAuthorizationAppleIDProviderCredentialAuthorized:
                        // 授权状态有效
                        break;
                    case ASAuthorizationAppleIDProviderCredentialRevoked:
                        // 苹果账号登录的凭据已被移除,需解除绑定并重新引导用户使用苹果登录
                        break;
                    case ASAuthorizationAppleIDProviderCredentialNotFound:
                        // 未登录授权,直接弹出登录页面,引导用户登录
                        break;
                    case ASAuthorizationAppleIDProviderCredentialTransferred:
                        // 授权AppleID提供者凭据转移
                        break;
                }
            }];
        }
        
    }
    
}

3.1、创建登录按钮(可以自己自定义按钮,也可以使用苹果原生按钮)
示例以苹果官方按钮演示(app登录页面创建)

//登录也引入头文件
#import <AuthenticationServices/AuthenticationServices.h>
//添加代理
@interface ViewController ()<ASAuthorizationControllerDelegate,ASAuthorizationControllerPresentationContextProviding>

@end

然后在viewDidLoad创建按钮

#pragma mark -  iOS13 才支持 系统提供的 登录按钮 要做下判断
        if (@available(iOS 13.0, *)){
//             Sign In With Apple 按钮
            ASAuthorizationAppleIDButton *appleIDBtn3 = [ASAuthorizationAppleIDButton buttonWithType:ASAuthorizationAppleIDButtonTypeDefault style:ASAuthorizationAppleIDButtonStyleWhiteOutline];
            appleIDBtn3.frame = CGRectMake(30, 560, self.view.bounds.size.width - 60, 40);
            
            [appleIDBtn3 addTarget:self action:@selector(didAppleIDBtnClicked) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:appleIDBtn3];
            
        }

运行结果显示
苹果登录按钮.png

按钮的颜色可以自行设置,黑的白的都有
3.2、点击事件触发的代理

#pragma mark - 苹果登录  发起授权登录请求   Begin    ================== https://www.jianshu.com/p/483b998f2370
-(void)didAppleIDBtnClicked{
    
    if (@available(iOS 13.0, *)) {
//        Authorization 发起授权登录请求
/*
 ASAuthorizationAppleIDProvider 这个类比较简单,头文件中可以看出,主要用于创建一个 ASAuthorizationAppleIDRequest 以及获取对应 userID 的用户授权状态。
 */
        ASAuthorizationAppleIDProvider * appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
        ASAuthorizationAppleIDRequest * authAppleIDRequest = [appleIDProvider createRequest];
//        ASAuthorizationPasswordRequest * passwordRequest = [[[ASAuthorizationPasswordProvider alloc] init] createRequest];

        NSMutableArray <ASAuthorizationRequest *> * array = [NSMutableArray arrayWithCapacity:2];
        if (authAppleIDRequest) {
            [array addObject:authAppleIDRequest];
        }
        NSArray <ASAuthorizationRequest *> * requests = [array copy];
        
        ASAuthorizationController * authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:requests];
        authorizationController.delegate = self;
        authorizationController.presentationContextProvider = self;
        [authorizationController performRequests];
        
    } else {
        // 处理不支持系统版本
        NSLog(@"系统不支持Apple登录");
    }
    
}
#pragma mark- ASAuthorizationControllerDelegate
// 授权成功
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {
    
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        
        ASAuthorizationAppleIDCredential * credential = authorization.credential;
        
//         苹果用户唯一标识符,该值在同一个开发者账号下的所有 App 下是一样的,开发者可以用该唯一标识符与自己后台系统的账号体系绑定起来。
        NSString * userID = credential.user;
//         苹果用户信息 如果授权过,可能无法再次获取该信息
        NSPersonNameComponents * fullName = credential.fullName;
        NSString * email = credential.email;
        
//         服务器验证需要使用的参数
        NSString * authorizationCode = [[NSString alloc] initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding];
        NSString * identityToken = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding];
        
//         用于判断当前登录的苹果账号是否是一个真实用户,取值有:unsupported、unknown、likelyReal
        ASUserDetectionStatus realUserStatus = credential.realUserStatus;
        
        [[NSUserDefaults standardUserDefaults] setObject:userID forKey:@"appleID"];
        
        NSLog(@"userID: %@", userID);
        NSLog(@"fullName: %@", fullName);
        NSLog(@"email: %@", email);
        NSLog(@"authorizationCode: %@", authorizationCode);
        NSLog(@"identityToken: %@", identityToken);
        NSLog(@"realUserStatus: %@", @(realUserStatus));
        
        NSString * loging = [NSString stringWithFormat:@"参数1:%@参数2:%@参数3:%@",userID,email,identityToken];
        NSLog(@"Sign in with Apple++++++++++%@",loging);
        
        
        
    }
    else if ([authorization.credential isKindOfClass:[ASPasswordCredential class]]) {
        
        // 用户登录使用现有的密码凭证
        ASPasswordCredential * passwordCredential = authorization.credential;
        // 密码凭证对象的用户标识 用户的唯一标识
        NSString * user = passwordCredential.user;
        // 密码凭证对象的密码
        NSString * password = passwordCredential.password;
        
        NSLog(@"userID: %@", user);
        NSLog(@"password: %@", password);
        
    } else {
        
    }
}

// 授权失败
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
    
    NSString *errorMsg = nil;
    
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"用户取消了授权请求";
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求响应无效";
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求失败未知原因";
            break;
    }
    NSLog(@"%@", errorMsg);
}

#pragma mark- ASAuthorizationControllerPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller  API_AVAILABLE(ios(13.0)){
    
    return self.view.window;
}

#pragma mark- apple授权状态 更改通知
- (void)handleSignInWithAppleStateChanged:(NSNotification *)notification
{
    NSLog(@"%@", notification.userInfo);
}
#pragma mark - 苹果授权    End    ========================

四、返回结果(上面已经向Apple id发起了请求,该返回给我们参数了,对吧!哈哈😄)

2021-07-10 11:46:57.941899+0800 SignInWithAppleZA[5704:1240072] Sign in with Apple++++++++++userID参数为:001921.36778e4680b8499bb1f87637ca300daa.0111email参数为:(null)identityToken参数为:eyJraWQiOiJZdXlYb1kiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL2FwcGxlaWQuYXBwbGUuY29tIiwiYXVkIjoiWm9uZ0FuZy5TaWduSW5XaXRoQXBwbGVaQSIsImV4cCI6MTYyNTk3NTIxNywiaWF0IjoxNjI1ODg4ODE3LCJzdWIiOiIwMDE5MjEuMzY3NzhlNDY4MGI4NDk5YmIxZjg3NjM3Y2EzMDBkYWEuMDExMSIsImNfaGFzaCI6IlByNllJbDRVbDd3OUJXVjdIVFlZV1EiLCJhdXRoX3RpbWUiOjE2MjU4ODg4MTcsIm5vbmNlX3N1cHBvcnRlZCI6dHJ1ZX0.eqjsrrybCHwxunceE7keAI0xju1Z0wxph3fJrBrPLNfxda1QR1jYTTto_0t4K2UZ1FzWVVhaHsP3z3hdUjZDugGxEfkyb1E2sZsqPYh2a7IfkBEq4hKhWDxqpQ_uPr133fBbuPnRbllRcUoE2I6p7n7HPu3u425RY97KIomyTI-94GzoQ04y6fx6cS9WEJQtjOnF2Y7tfMDiPIaXzrK5f5lcVAvhxEkwcCPoLM8qsne8zJENcM_a_2VcsyFG3262hz9uIFBupL_IYZcXjsfZXtlXYVCqH2NLVpN4JAzewmD5Pg9KRRAkFEjB_zWhvdymffe1Xpc8GCAN2Q8FpbambA

4.0、控制台打印结果
控制台打印结果.png

总结:基本上就是这样的流程操作

有文化的程序员.png

五、本篇代码地址已上传git

帅气十足的小伙子

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容