Implement Sign In with Apple button in Swift
“Sign In with Apple” is a new way for users to create accounts and sign in into iOS apps. In this iOS tutorial we are going to learn how to implement the Sign in with Apple button in Swift.
Let’s Start
- Open Xcode and create a new project
2. Go to Project Navigator → Select Project → Select Target
3. In Project Editor click Signing & Capabilities
4. Add Capability by clicking + button and search for Sign In with Apple Capability. Double click on capability to add.
Once you double click on capability the Sign In with Apple capability added to your project and you will see the SignInWithApple.entitlements in your project.
5. Import AuthenticationServices framework to give users the ability to sign into your app services with their Apple ID.
import AuthenticationServices
6. Add Sign In with Apple button using below code and call setupSignInWithAppleButton function in viewDidLoad.
func setupSignInWithAppleButton() {let authButton = ASAuthorizationAppleIDButton()authButton.frame = CGRect.init(x: 50, y: self.view.frame.height/2 - 25, width: self.view.frame.width - 100, height: 50)authButton.addTarget(self, action: #selector(actionOnSignInWithAppleIDButton), for: .touchUpInside)self.view.addSubview(authButton)}
7. We have given a target function to the button which will be called when the button is clicked. Let’s call this actionOnSignInWithAppleIDButton.
@objc func actionOnSignInWithAppleIDButton() {let provider = ASAuthorizationAppleIDProvider()let request = provider.createRequest()request.requestedScopes = [.fullName,.email]let authVC = ASAuthorizationController.init(authorizationRequests: [request])authVC.presentationContextProvider = selfauthVC.delegate = selfauthVC.performRequests()}
In the above function we are creating a request using ASAuthorizationAppleIDProvider and in requestScopes we will asking the user for full name and email. After that we will initialize a controller ASAuthorizationController to perform the request.
8. Let’s add delegate ASAuthorizationControllerDelegate to handle authorization result and error.
extension ViewController: ASAuthorizationControllerDelegate {func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential else {return}let id = appleIDCredential.userlet email = appleIDCredential.emaillet firstName = appleIDCredential.fullName?.givenName ?? ""let lastName = appleIDCredential.fullName?.familyName ?? ""let name = firstName + lastNameprint(appleIDCredential)let result = String("User ID:\(id)\nEmail:\(email)\nName:\(name)")print(result)}func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {print(error.localizedDescription)}}
9. Add ASAuthorizationControllerPresentationContextProviding which is used to telling the app to show the authorization view on a particular window.
extension ViewController: ASAuthorizationControllerPresentationContextProviding{func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {return self.view.window!}}
On successful authorization, we get user information which has user identifier. We can use that identifier to check the user’s credential state by calling the getCredentialState(forUserID: userId) method
let appleIDProvider = ASAuthorizationAppleIDProvider()appleIDProvider.getCredentialState(forUserID: userID) { (state, error) inswitch state {case .authorized: // The Apple ID credential is valid.breakcase .revoked: // The credential is revoked.breakcase .notFound:// No credential was foundbreakdefault: break}}
Build and run the app, you will get following result
Thanks for reading 😊
Code