Skip to content

Instantly share code, notes, and snippets.

@ranmyfriend
Created March 11, 2017 20:22
Show Gist options
  • Save ranmyfriend/309f9067b20630671d975bd16c13dc26 to your computer and use it in GitHub Desktop.
Save ranmyfriend/309f9067b20630671d975bd16c13dc26 to your computer and use it in GitHub Desktop.
AddressBook Integration using CNContactStore in Swift 3
//
// AddressBookHelper.swift
// AddressBook
//
// Created by Ranjith Kumar on 11/03/2017.
// Copyright © 2017 F22Labs. All rights reserved.
//
import Foundation
import Contacts
enum ABAuthorizationStatus:Int {
case authorized
case denied
case notDetermined
}
protocol AddressBookHelperProtocol:class {
func contactsAreLoaded(contacts:[contactModel])
}
class AddressBookHelper:NSObject {
public weak var delegate:AddressBookHelperProtocol?
func isContactsAuthorized(completion:@escaping ((ABAuthorizationStatus)->())) {
let status = CNContactStore.authorizationStatus(for: .contacts)
switch status {
case .notDetermined:
let contactStore = CNContactStore.init()
contactStore.requestAccess(for: .contacts, completionHandler: { (status, error) in
if status {
self.loadContacts()
}else {
completion(.denied)
}
})
case .authorized: self.loadContacts(); break
case .denied,
.restricted:
completion(.denied)
break
}
}
func loadContacts() {
let contactStore = CNContactStore.init()
let keys = [CNContactPhoneNumbersKey,CNContactGivenNameKey,CNContactImageDataKey]
let request = CNContactFetchRequest.init(keysToFetch: keys as [CNKeyDescriptor])
var contacts:[contactModel] = []
try! contactStore.enumerateContacts(with: request) { (contact, stop) in
for object:CNLabeledValue in contact.phoneNumbers {
let mobileObject = object.value
let mobile = mobileObject.value(forKey: "digits") as? String
var givenName = contact.givenName
if givenName.isEmpty == true {
givenName = "Unknown"
}
let cmodel = contactModel.init(name: givenName, phone: mobile!)
contacts.append(cmodel)
}
}
self.delegate?.contactsAreLoaded(contacts: contacts)
}
}
class contactModel:NSObject {
var name:String?
var phone:String?
var selected:Bool?
init(name:String,phone:String) {
self.name = name
self.phone = phone
self.selected = false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment