The new Authentication system of Apple available to iOS 13 bring a security to users. Here you will learn how implement that.
Important:
Only available to iOS 13.0+, macOS 10.15+, tvOS 13.0+, watchOS 6.0+.
You need the last Xcode 11 Beta.
The Apple ID Account need 2FA.
1. Add Button Sign in
Create a new empty project (Single View App) and in the ViewController.swift:
import AuthenticationServices
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Add Sign in Button
let buttonAuth = ASAuthorizationAppleIDButton(authorizationButtonType: .default, authorizationButtonStyle: .black)
buttonAuth.addTarget(self, action: #selector(signInAppleID), for: .touchUpInside)
view.addSubview(buttonAuth)
buttonAuth.center = view.center
}
}
This button will be showed:
Other buttons avaliable:
let buttonAuth = ASAuthorizationAppleIDButton(
authorizationButtonType: .continue,
authorizationButtonStyle: .black)
let buttonAuth = ASAuthorizationAppleIDButton(
authorizationButtonType: .signUp,
authorizationButtonStyle: .black)
2. Add the sign in function
You can choice for scopes, like .email, .fullName.
@objc func signInAppleID() {
let appleIDProvider = ASAuthorizationAppleIDProvider()
let authRequest = appleIDProvider.createRequest()
authRequest.requestedScopes = [.email, .fullName]
let authController = ASAuthorizationController(authorizationRequests: [authRequest])
authController.presentationContextProvider = self
authController.delegate = self
authController.performRequests()
}
3. Getting data
Implementing the delegate, will return appleIDCredential, you can use the user informations (email, name) OR use the authorizationCode to your backend to validate the user, like oAuth2.
extension ViewController: ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential else { return }
print("User: \(appleIDCredential.user)")
print("Email: \(appleIDCredential.email!)")
print("Name: \(appleIDCredential.fullName!)")
print("Code: \(appleIDCredential.authorizationCode!)")
}
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return view.window!
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
// Fall back to login UI.
}
}
4. Capabilities
Go to your app target -> tab Signing & Capabilities and add Sign in with Apple: (Command + Shift + L)
Done! Just run your project!
I hope this helps you, if you have questions of suggestions, comment here or call me in my social networks.