与Apple登录:如何为现有应用实现此功能?

时间:2019-06-04 11:25:42

标签: ios apple-sign-in

随着Apple在2019年6月3日发布的最新重大更新,有一项功能Sign In with Apple。应用中提供了有关“如何使用此功能”的信息,但我可以看到任何示例源代码,以及如何在现有的iOS应用中实现此功能。

我正在寻找示例源代码,因为我不知道如何开始。

我尝试过的方法:Sign In with Apple

1 个答案:

答案 0 :(得分:4)

第一步是您需要import AuthenticationServices

如何检查用户凭证状态

        let appleIDProvider = ASAuthorizationAppleIDProvider()
        appleIDProvider.getCredentialState(forUserID: KeychainItem.currentUserIdentifier) { (credentialState, error) in
            switch credentialState {
            case .authorized:
                // The Apple ID credential is valid.
                break
            case .revoked:
                // The Apple ID credential is revoked.
                break
            case .notFound:
                // No credential was found, so show the sign-in UI.

            default:
                break
            }
        }

如何使用Apple创建登录名

第1步

如果找到现有的iCloud钥匙串凭证或Apple ID凭证,则提示用户。实施ASAuthorizationControllerDelegate

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()
}

extension ViewController: ASAuthorizationControllerDelegate {
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
         //here is credentials . 
        }
    }
}

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

第二步

创建按钮

    let authorizationButton = ASAuthorizationAppleIDButton()
    authorizationButton.addTarget(self, action: #selector(handleAuthorizationAppleIDButtonPress), for: .touchUpInside)

Step3

@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()
}

可用性 iOS 13或更高版本

演示应用程序:Github上提供了具有钥匙串集成功能的完整的演示应用程序-https://github.com/developerinsider/Sign-In-with-Apple-Demo

注意:我很快会用越来越多的有用信息来更新答案。

希望这会有所帮助。