Guides
Last updated
April 23, 2024

Firebase Email Verification on iOS Devices

Jim Tryon

Table of Contents:

Get your free
Email Validation
API key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Implementing Email Verification on Your Apple ID/iCloud with Firebase

One of the most popular and efficient methods to achieve email verification on your iOS devices is through Firebase Authentication. Firebase provides a comprehensive set of tools that make implementing real-time email verification straightforward and secure. 

Let’s send your first free
Email Validation
call
See why the best developers build on Abstract
Get your free api

Firebase Authentication

Create a Firebase Project:

Go to the Firebase Console. Click on "Add project," and follow the prompts to create a new Firebase project.

Add Your App to the Firebase Project:

Click on the iOS icon to add an iOS app to your Firebase project. Enter your app's bundle ID. You can find this in your Xcode project's target settings. Download the GoogleService-Info.plist file and add it to your Xcode project.

Install Firebase SDK:

Open your Xcode project and navigate to the Podfile. Add pod 'Firebase/Auth' to your Podfile. Run pod install in your terminal to install the Firebase Auth SDK.

Initialize Firebase in Your App:

Import Firebase in your AppDelegate.swift or SceneDelegate.swift file: import Firebase.

Add FirebaseApp.configure() to your initialization method (application(_:didFinishLaunchingWithOptions:) or scene(_:willConnectTo:options:)).

Real-Time Verification

To verify if a user has clicked the verification link in real-time, you can periodically check the user's Apple ID email verification status:


func checkVerification() {
Auth.auth().currentUser?.reload { error in
if let error = error {
print("Error reloading user: \(error.localizedDescription)")
} else if Auth.auth().currentUser?.isEmailVerified == true {
print("Email is verified.")
// Proceed with the app's flow
}
}
}

Handling Verification:

Guide the user to check their email  on their Mac, iPad, or iPhone device and click the verification link. Provide a button or mechanism in your app to allow users to request another verification email if needed. Implement a method to check if the user has verified their email before allowing them to proceed with certain features of your app found in the app store.

Testing and Deployment:

Test the email verification process thoroughly with different email accounts. Monitor for any issues or user feedback related to the email verification process and adjust your implementation as necessary.

Comparison Table of Firebase Authentication vs. Custom Verification Methods

FeatureFirebase AuthenticationCustom Verification MethodsIntegration EaseEasy to integrate with comprehensive documentation and SDKs.Requires more effort and custom coding, depending on requirements.MaintenanceManaged by Firebase, with automatic updates and maintenance.Requires ongoing maintenance and updates by your team.CustomizationLimited customization options for the authentication flow and email templates.High level of customization for every aspect of the process.ScalabilityHighly scalable, leveraging Google’s infrastructure.Depends on the infrastructure and resources allocated.CostFree tier available; paid plans based on usage.Costs vary based on infrastructure, resources, and third-party services used.SecurityHigh level of security with continuous updates from Firebase.Dependent on the implementation and maintenance of security measures.Time to MarketQuicker to implement, allowing for faster deployment.Potentially longer development time due to custom solutions.Support and CommunityExtensive support through Firebase documentation, forums, and communities.Support depends on the specific technologies and libraries used.DependencyDependent on Firebase and Google’s infrastructure.No dependency on external services, unless third-party services are used.User ExperienceConsistent and predictable user experience predefined by Firebase.Fully customizable user experience tailored to app requirements.ComplianceFirebase complies with major regulations, which can simplify compliance efforts.Compliance responsibilities are fully managed by your team, which can be more flexible but demanding.

Code Examples and Best Practices

Let's dive deeper into how to implement email verification with Firebase in an iPhone or iPad app, including a custom verification process (could be via user’s phone number) and real-time feedback for users. We'll focus on Swift code examples and best practices to ensure a smooth and secure implementation.

Firebase Email Verification Code Example

First, ensure you have completed the setup for Firebase in your project as outlined in previous steps. Then, you can proceed with the following implementation details.

User Registration and Sending Verification Email


import FirebaseAuth

func registerUserWithEmail(email: String, password: String) {
Auth.auth().createUser(withEmail: email, password: password) { (authResult, error) in
if let error = error {
print("Error creating user: \(error.localizedDescription)")
} else {
// User created, verification email sent
}
}
}

func sendVerificationEmail() {
Auth.auth().currentUser?.sendEmailVerification { error in
if let error = error {
print("Error sending verification email: \(error.localizedDescription)")
} else {
print("Verification email sent.")
}
}
}

Custom Verification Process

While Firebase handles the email sending, you might want to customize the user experience around this process. For example, guiding the user through the verification process with customized screens or messages.

Guide for Custom Screens

Verification Screen: After the user signs up, navigate them to a screen that explains a verification email has been sent. Provide clear instructions on what they need to do next.

Resend Email Functionality: Offer the ability to resend the verification email. This is helpful if the email didn't arrive or was sent to spam by accident.



func resendVerificationEmail() {
sendVerificationEmail() // Reuse the sendVerificationEmail function.
}

Real-Time Feedback Implementation

To enhance user experience, provide real-time feedback on the email verification status. You can do this by periodically checking if the user has verified their email.

Checking Email Verification Status


func checkEmailVerification() {
Auth.auth().currentUser?.reload { [weak self] error in
if let user = Auth.auth().currentUser, user.isEmailVerified {
// Email is verified. Update the UI or proceed to the next screen.
print("Email verified.")
} else {
// Email not verified. Keep user on the verification screen or show a message.
print("Email not verified yet.")
}
}
}

To automate this, you might set up a timer to periodically call checkEmailVerification, providing real-time feedback to the user. However, be mindful of the user experience and network usage. 

Additional Resources

How to Include AbstractAPI’s Email Validation Into an iPhone or iPad App

Incorporating AbstractAPI into an iPhone or iPad application involves a few steps. The AbstractAPI Email Validation API provides a straightforward way to validate new Apple ID email addresses in real-time. Here’s a guide to help you integrate this functionality into your iOS 17 app:

Step 1: Obtain an API Key from AbstractAPI

First, you need to sign up for AbstractAPI and obtain an API key for the Email Validation API. This key is essential for making requests to their service.

Visit AbstractAPI’s Email Validation page. Sign up or log in to create a new API key.

Step 2: Setting Up Your iOS 17 Project

Ensure your iOS project is ready to make network requests. If you’re using URLSession, no additional setup is required. However, if you plan to use a third-party library like Alamofire for networking, ensure it is installed in your project.

Step 3: Making a Request to the Email Validation API

You can use URLSession to make a GET request to the AbstractAPI’s Email Validation endpoint. Here’s how you can do it with Swift:


import Foundation

func validateEmail(email: String, completion: @escaping (Bool, String?) -> Void) {
let apiKey = "YOUR_API_KEY_HERE"
let urlString = "https://emailvalidation.abstractapi.com/v1/?api_key=\(apiKey)&email=\(email)"
guard let url = URL(string: urlString) else {
completion(false, "Invalid URL")
return
}

let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
completion(false, "Network request failed")
return
}

do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let isValid = json["is_valid_format"] as? [String: Any],
let value = isValid["value"] as? Bool {
completion(value, nil)
} else {
completion(false, "Error parsing response")
}
} catch {
completion(false, "Error decoding response")
}
}
task.resume()
}

Replace "YOUR_API_KEY_HERE" with your actual API key from AbstractAPI.

This function makes a network request to the Email Validation API and passes the result to a completion handler. It checks if the email is valid based on the response from AbstractAPI.

Step 4: Handling the Validation Response

Use the validateEmail function where you need to validate an email address. For instance, you might call it when a user submits a registration form:


validateEmail(email: "test@example.com") { isValid, errorMessage in
DispatchQueue.main.async {
if let errorMessage = errorMessage {
print("Error: \(errorMessage)")
} else if isValid {
print("The email is valid.")
// Proceed with registration or email verification.
} else {
print("The email is invalid.")
// Show an error message to the user.
}
}
}

Jim Tryon

Jim Tryon is an iOS developer with expertise in building user-friendly apps. He writes about topics like iPhone email verification, sharing insights into efficient app development.

Get your free
Email Validation
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
Email Validation
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required