iOS13 Sign In with Apple

2020-03-26  本文已影响0人  love断鸿

在WWDC 2019,苹果推出了Sign In with Apple这一iOS 13的新特性,并在2020年4月底前,强制App适配
Sign In with Apple可以让用户可以直接利用苹果ID登陆应用,免去了输入邮箱、密码,验证登陆邮箱等繁琐的步骤, 同时Sign In with Apple提供了跨平台特性和安全性的提高。

先来看看什么样的App需要适配Sign In with Apple

看了下审核条款

4.8 通过 Apple 登录
如果 app 使用第三方或社交登录服务 (例如,Facebook 登录、Google 登录、通过 Twitter 登录、通过 LinkedIn 登录、通过 Amazon 登录或微信登录) 来对其进行设置或验证这个 app 的用户主帐户,则该 app 必须同时提供“通过 Apple 登录”作为同等选项。用户的主帐户是指在 app 中建立的、用于标识身份、登录和访问功能和相关服务的帐户。

在以下情况下,可以不适配

您的 app 仅使用公司自有的帐户设置和登录系统。
您的 app 是一款教育、企业或商务 app,要求用户使用现有的教育或企业帐户登录。
您的 app 使用政府或行业支持的公民身份系统或电子身份证来鉴定用户身份。
您的 app 是特定第三方服务的客户端,用户需要使用他们的邮件、社交媒体或其他第三方帐户直接登录才能访问内容。

流程图

自己用Pages画的 凑合看吧😀


image.png
步骤

1:项目的配置: 开通苹果登录的权限


image.png

2:直接上代码

import AuthenticationServices

创建Button

 let btnApple = ASAuthorizationAppleIDButton (authorizationButtonType: ASAuthorizationAppleIDButton.ButtonType.signIn,authorizationButtonStyle: ASAuthorizationAppleIDButton.Style.whiteOutline)

btnApple.addTarget.....

ASAuthorizationAppleIDButton 这个东西是苹果专门为Sign In with Apple 设计的Button 除了他给定的几种 Style之外, 不可以更改(圆角除外),哪怕是有点丑, 当然你也可以自定义按钮,但是审核能不能过 就另当别论了
下面是官方Demo的代码

import UIKit
import AuthenticationServices

class LoginViewController: UIViewController {
    
    @IBOutlet weak var loginProviderStackView: UIStackView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupProviderLoginView()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        performExistingAccountSetupFlows()
    }
    
    func setupProviderLoginView() {
        let authorizationButton = ASAuthorizationAppleIDButton()
        authorizationButton.addTarget(self, action: #selector(handleAuthorizationAppleIDButtonPress), for: .touchUpInside)
        self.loginProviderStackView.addArrangedSubview(authorizationButton)
    }
    
    /// Prompts the user if an existing iCloud Keychain credential or Apple ID credential is found.
    func performExistingAccountSetupFlows() {
        // Prepare requests for both Apple ID and password providers.
        let requests = [ASAuthorizationAppleIDProvider().createRequest(),
                        ASAuthorizationPasswordProvider().createRequest()]
        
        // Create an authorization controller with the given requests.
        let authorizationController = ASAuthorizationController(authorizationRequests: requests)
        authorizationController.delegate = self
        authorizationController.presentationContextProvider = self
        authorizationController.performRequests()
    }
    
    @objc
    func handleAuthorizationAppleIDButtonPress() {
        let appleIDProvider = ASAuthorizationAppleIDProvider()
        let request = appleIDProvider.createRequest()
        request.requestedScopes = [.fullName, .email]
        
        let authorizationController = ASAuthorizationController(authorizationRequests: [request])
        authorizationController.delegate = self
        authorizationController.presentationContextProvider = self
        authorizationController.performRequests()
    }
}

extension LoginViewController: ASAuthorizationControllerDelegate {
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
            
            let userIdentifier = appleIDCredential.user
            let fullName = appleIDCredential.fullName
            let email = appleIDCredential.email
            
            // Create an account in your system.
            // For the purpose of this demo app, store the userIdentifier in the keychain.
            do {
                try KeychainItem(service: "com.example.apple-samplecode.juice", account: "userIdentifier").saveItem(userIdentifier)
            } catch {
                print("Unable to save userIdentifier to keychain.")
            }
            
            // For the purpose of this demo app, show the Apple ID credential information in the ResultViewController.
            if let viewController = self.presentingViewController as? ResultViewController {
                DispatchQueue.main.async {
                    viewController.userIdentifierLabel.text = userIdentifier
                    if let givenName = fullName?.givenName {
                        viewController.givenNameLabel.text = givenName
                    }
                    if let familyName = fullName?.familyName {
                        viewController.familyNameLabel.text = familyName
                    }
                    if let email = email {
                        viewController.emailLabel.text = email
                    }
                    self.dismiss(animated: true, completion: nil)
                }
            }
        } else if let passwordCredential = authorization.credential as? ASPasswordCredential {
            // Sign in using an existing iCloud Keychain credential.
            let username = passwordCredential.user
            let password = passwordCredential.password
            
            // For the purpose of this demo app, show the password credential as an alert.
            DispatchQueue.main.async {
                let message = "The app has received your selected credential from the keychain. \n\n Username: \(username)\n Password: \(password)"
                let alertController = UIAlertController(title: "Keychain Credential Received",
                                                        message: message,
                                                        preferredStyle: .alert)
                alertController.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
                self.present(alertController, animated: true, completion: nil)
            }
        }
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // Handle error.
        var errorMsg:String = "";
        
        switch ((error as! ASAuthorizationError).code) {

        case .canceled:
            errorMsg = "用户取消了授权请求";
            break;
        case .failed:
            errorMsg = "授权请求失败";
            break;
        case .invalidResponse:
            errorMsg = "授权请求响应无效";
            break;
        case .notHandled:
            errorMsg = "未能处理授权请求";
            break;
        case .unknown:
            errorMsg = "授权请求失败未知原因";
            break;

        default:
            errorMsg = "默认";
        }
    }
}

extension LoginViewController: ASAuthorizationControllerPresentationContextProviding {
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return self.view.window!
    }
}

没什么好解释的 都很简单
官方Demo地址

上一篇下一篇

猜你喜欢

热点阅读