随着 Apple 于 2019 年 6 月 3 日发布的最新重大更新,有一项功能Sign In with Apple。有关“如何在应用程序中使用”的信息是可用的,但我可以看到任何示例源代码,如何在您现有的 iOS 应用程序中实现此功能。
我正在寻找一个示例源代码,因为我不明白如何开始。
以及我尝试过的:使用 Apple 登录
随着 Apple 于 2019 年 6 月 3 日发布的最新重大更新,有一项功能Sign In with Apple。有关“如何在应用程序中使用”的信息是可用的,但我可以看到任何示例源代码,如何在您现有的 iOS 应用程序中实现此功能。
我正在寻找一个示例源代码,因为我不明白如何开始。
以及我尝试过的:使用 Apple 登录
第一步是你需要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
}
}
第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!
}
}
第2步:
创建按钮
let authorizationButton = ASAuthorizationAppleIDButton()
authorizationButton.addTarget(self, action: #selector(handleAuthorizationAppleIDButtonPress), for: .touchUpInside)
第三步
@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 或更高版本
Demo Application: A complete working demo application with keychain integration available on Github - https://github.com/developerinsider/Sign-In-with-Apple-Demo
Note: I will update answer with more and more useful information soon.
Hope it is helpful .