iOS开发 - 集成苹果登录功能(Sign In With Apple)

一、 配置项目使其支持苹果登录功能

  1. 配置Identifiers
    链接
    找到项目对应的id,点击进入编辑页面,选中此项
    Sign In With Apple
  2. 重新生成Profiles(执行上一步操作之后,描述文件会过期),点进去之后保存一下,下载下来双击激活就ok了
  3. 配置项目


    配置项目1
配置项目2

二、代码部分

  1. 苹果登录按钮(必须要使用苹果提供的按钮,不能使用UIButton 否则可能会被拒)
    注:有的文章说如果样式和系统的差不大多的话也可以,这个笔者没有做验证,第一次使用UIButton的时候是被拒了
    注意:苹果登录只在iOS13之后可用
import AuthenticationServices

func setupLoginB() {
    if #available(iOS 13.0, *) {
        let appleIdLoginB = ASAuthorizationAppleIDButton(authorizationButtonType: .signIn, authorizationButtonStyle: .black)
        appleIdLoginB.cornerRadius = 20
        appleIdLoginB.addTarget(self, action: #selector(appleIdLoginAction), for: .touchUpInside)
        addSubview(appleIdLoginB)
    }
}

  1. 登录的逻辑
@objc func appleIdLoginAction() {
     if #available(iOS 13.0, *) {
            let appleIDProvider = ASAuthorizationAppleIDProvider()
            let request = appleIDProvider.createRequest()
            request.requestedScopes = [.fullName, .email]
            let auth = ASAuthorizationController(authorizationRequests: [request])
            auth.delegate = self
            auth.presentationContextProvider = self
            auth.performRequests()
      }
}
  1. 实现代理
extension LoginController: ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
    @available(iOS 13.0, *)
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return self.view.window!
    }
    
    @available(iOS 13.0, *)
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        var user: String? = nil
        if let apple = authorization.credential as? ASAuthorizationAppleIDCredential {
            user = apple.user
            
        } else if let password = authorization.credential as? ASPasswordCredential {
            user = password.user
        }
        
        guard let u = user else { makeToast("苹果登陆异常!"); return }
        // 将u传给后台来进行后续操作
        // 后台根据需求来判断是否需要去验证user 笔者暂时没有做验证 只是暂时将user绑定,审核暂时没有问题
    }
    
    @available(iOS 13.0, *)
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        print(error)
    }
}

你可能感兴趣的:(iOS开发 - 集成苹果登录功能(Sign In With Apple))