刚开始学习接入苹果登录,网上搜索了一些帖子,没一个直接可用的,帖子质量我就不吐槽了。
只好去苹果开发者官网去探索,官网提供了demo,下载、运行一次通过。
demo里与我无关的代码,都删掉了,只剩下简简单单几十行即可实现苹果登录。
第一次写技术帖子,如果觉得内容质量不错,请点个赞再走哦!!!
有两处需要配置:
苹果开发者后台Identifiers需要选中Sign in with Apple后保存即可(前提是Xcode里设置的Automatically manage signing)。
项目TARGETS -> Signing & Capabilities需要添加Sign in with Apple。
项目代码如下,可直接复制使用:
import UIKit
import AuthenticationServices//导入苹果认证服务框架
class LoginAppleVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//显示Apple ID登录窗口,一般是点击苹果登录按钮后弹出
//我是为了方便演示,所以放在这里
performExistingAccountSetupFlows()
}
//显示Apple ID登录窗口
func performExistingAccountSetupFlows() {
let requests = [ASAuthorizationAppleIDProvider().createRequest()]//我只用到ID登录
let authorizationController = ASAuthorizationController(authorizationRequests: requests)
authorizationController.delegate = self
authorizationController.presentationContextProvider = self
authorizationController.performRequests()
}
}
//扩展LoginAppleVC
extension LoginAppleVC: ASAuthorizationControllerDelegate {
//授权成功回调
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
switch authorization.credential {
case let appleIDCredential as ASAuthorizationAppleIDCredential://我只用到ID登录
//获取的userIdentifier可接入自己的账户系统,我用的LeanCloud平台
//我只需要userIdentifier
let userIdentifier = appleIDCredential.user
print("授权成功:userIdentifier = \(userIdentifier)")
default:
break
}
}
//授权失败回调
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
//处理错误
print("授权失败:error = \(error)")
}
}
extension LoginAppleVC: ASAuthorizationControllerPresentationContextProviding {
//提供弹窗根视图
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return self.view.window!
}
}