通过 Apple 登录

通过 Apple 登录

一、苹果开发者后台配置
选择Identifiers
勾选Sign In With Apple

二、Xcode配置
Signing & Capabiliteds -> Capability -> Sign ln with Apple

三、代码实现
1、引入头文件
#import 

2、遵守协议


3、授权请求
if (@available(iOS 13.0, *)) {
    ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
    ASAuthorizationOpenIDRequest *request = appleIDProvider.createRequest;
    request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
    
    ASAuthorizationController *controller = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
    controller.delegate = self;
    [controller performRequests];
}

4、实现相关代理方法
#pragma mark - ASAuthorizationControllerDelegate
- (void)authorizationController:(ASAuthorizationController *)controller
   didCompleteWithAuthorization:(ASAuthorization *)authorization  API_AVAILABLE(ios(13.0)){
    NSMutableDictionary *dictInfo = [NSMutableDictionary dictionary];
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        ASAuthorizationAppleIDCredential *appleIDCredential = authorization.credential;
        [dictInfo setValue:appleIDCredential.identityToken
                    forKey:@"identity_token"];
        [dictInfo setValue:appleIDCredential.user
                    forKey:@"user"];
    }
}

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

参考文章 - iOS开发:Sign In With Apple(使用Apple登录)
参考文章 - iOS 苹果第三方登录
参考文章 - 4.8 - 使用Apple登录

你可能感兴趣的:(通过 Apple 登录)