Getting the birth date of current user with Swift

Building a quality software means providing a good user experience. I encourage all developers embracing and following macOS Human Interface Guidelines. Or, reading it at least :-)

Say, we're building an macOS application that requires the user's age information to be able to work correctly. So why bothering users to provide that data instead of fetching it from users' contacts?

I'm sharing a simplified Swift 3 code snippet below. Calling getUserDetails requests user's permissions to access contacts with the Contacts framework.

If authorized, it tries to find a contact with the full name of the current user.

import Foundation  
import Contacts


func requestForAccess(completionHandler: @escaping (_ accessGranted: Bool) -> Void) {  
    let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)

    switch authorizationStatus {
    case .authorized:
        completionHandler(true)

    case .denied, .notDetermined:
        let contactStore = CNContactStore()

        contactStore.requestAccess(for: CNEntityType.contacts, completionHandler: { (access, accessError) -> Void in
            if access {
                completionHandler(access)
            }
            else {
                if authorizationStatus == CNAuthorizationStatus.denied {
                    let queue = DispatchQueue(label: "com.app.queue")
                    queue.async() {
                        let message = "\(accessError!.localizedDescription)\n\nPlease allow the app to access your contacts through the Settings."
                        print(message)
                    }
                }
            }
        })

    default:
        completionHandler(false)
    }
}

func getUserDetails() {  
    requestForAccess { (accessGranted) -> Void in
        if accessGranted {
            let predicate = CNContact.predicateForContacts(matchingName: NSFullUserName())
            let keys = [CNContactBirthdayKey]

            do {
                let contactStore = CNContactStore()
                let contacts = try contactStore.unifiedContacts(matching: predicate, keysToFetch: keys as [CNKeyDescriptor])

                if contacts.count == 0 {
                    print("No contacts were found matching the given name.")
                } else {
                    for contact in contacts {
                        print(contact.birthday)
                    }
                }
            }
            catch {
                print("Unable to fetch contacts.")
            }
        }
    }
}

You're welcome to share ideas how to get the user's gender information.

Michael Samoylov

Python, JavaScript and Swift Expert with 12+ years of experience.

Vilnius, Lithuania https://monmar.tech

Subscribe to Michael Samoylov

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!