Created
June 30, 2015 11:33
-
-
Save ArchieGoodwin/982146dc0957d14c824c to your computer and use it in GitHub Desktop.
Address Book helper in swift (create contact, get contact, add to group and so on)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//MARK: Address Book methods | |
func createAddressBook() -> Bool { | |
if self.adbk != nil { | |
return true | |
} | |
var err : Unmanaged<CFError>? = nil | |
let adbk : ABAddressBook? = ABAddressBookCreateWithOptions(nil, &err).takeRetainedValue() | |
if adbk == nil { | |
print(err) | |
self.adbk = nil | |
return false | |
} | |
self.adbk = adbk | |
return true | |
} | |
func determineStatus() -> Bool { | |
let status = ABAddressBookGetAuthorizationStatus() | |
switch status { | |
case .Authorized: | |
return self.createAddressBook() | |
case .NotDetermined: | |
var ok = false | |
ABAddressBookRequestAccessWithCompletion(nil) { | |
(granted:Bool, err:CFError!) in | |
dispatch_async(dispatch_get_main_queue()) { | |
if granted { | |
ok = self.createAddressBook() | |
} | |
} | |
} | |
if ok == true { | |
return true | |
} | |
self.adbk = nil | |
return false | |
case .Restricted: | |
self.adbk = nil | |
return false | |
case .Denied: | |
self.adbk = nil | |
return false | |
} | |
} | |
func createGroup(groupName: String) -> ABRecordRef { | |
let groupRecord: ABRecordRef = ABGroupCreate().takeRetainedValue() | |
let allGroups = ABAddressBookCopyArrayOfAllGroups(adbk).takeRetainedValue() as Array | |
for group in allGroups { | |
let currentGroup: ABRecordRef = group | |
let currentGroupName = ABRecordCopyValue(currentGroup, kABGroupNameProperty).takeRetainedValue() as! String | |
if (currentGroupName == groupName) { | |
print("Group exists") | |
return currentGroup | |
} | |
} | |
ABRecordSetValue(groupRecord, kABGroupNameProperty, groupName, nil) | |
ABAddressBookAddRecord(adbk, groupRecord, nil) | |
ABAddressBookSave(adbk, nil) | |
print("Made group") | |
return groupRecord | |
} | |
func addPersonToGroup(mainContact: ABRecordRef) { | |
let groupName = "Main Contacts" | |
let group: ABRecordRef = createGroup(groupName) | |
if let groupMembersArray = ABGroupCopyArrayOfAllMembers(group) { | |
let groupMembers = groupMembersArray.takeRetainedValue() as Array | |
for member in groupMembers { | |
let currentMember: ABRecordRef = member | |
if currentMember === mainContact { | |
print("Already in it.") | |
return | |
} | |
} | |
} | |
print(mainContact) | |
let addedToGroup = ABGroupAddMember(group, mainContact, nil) | |
if !addedToGroup { | |
print("Couldn't add person to group.") | |
} | |
ABAddressBookSave(adbk, nil) | |
} | |
func makeAndAddPersonRecord(person: MainContact) { | |
var profType : ProfileType = ProfileType.Basic | |
if let shared = person.profileType | |
{ | |
if shared == "Business" | |
{ | |
profType = ProfileType.Business | |
} | |
if shared == "Social" | |
{ | |
profType = ProfileType.Social | |
} | |
} | |
let personRecord: ABRecordRef = ABPersonCreate().takeRetainedValue() | |
ABRecordSetValue(personRecord, kABPersonFirstNameProperty, person.firstname, nil) | |
ABRecordSetValue(personRecord, kABPersonLastNameProperty, person.lastname, nil) | |
let phones = helper.phonesForUserAndProfileType(person, profile: profType) | |
if(phones?.count > 0) | |
{ | |
let addr:ABMultiValue = ABMultiValueCreateMutable(ABPropertyType(kABStringPropertyType)).takeRetainedValue() | |
let phonesArray : [Phones] = phones! | |
for phone in phonesArray | |
{ | |
if let phoneT = phone.phoneType | |
{ | |
if phoneT == "Mobile" | |
{ | |
ABMultiValueAddValueAndLabel(addr, phone.phone, kABPersonPhoneMobileLabel, nil) | |
} | |
if phoneT == "Landline" | |
{ | |
ABMultiValueAddValueAndLabel(addr, phone.phone, kABPersonPhoneMainLabel, nil) | |
} | |
} | |
} | |
ABRecordSetValue(personRecord, kABPersonPhoneProperty, addr, nil) | |
} | |
let emails = helper.emailsForUserAndProfileType(person, profile: profType) | |
if(emails?.count > 0) | |
{ | |
let emailRef:ABMultiValue = ABMultiValueCreateMutable(ABPropertyType(kABStringPropertyType)).takeRetainedValue() | |
let emailsArray : [Emails] = emails! | |
for email in emailsArray | |
{ | |
if(email.email != nil) | |
{ | |
ABMultiValueAddValueAndLabel(emailRef, email.email, kABWorkLabel, nil) | |
} | |
} | |
ABRecordSetValue(personRecord, kABPersonEmailProperty, emailRef, nil) | |
} | |
var error: Unmanaged<CFErrorRef>? = nil | |
let couldAddPerson = ABAddressBookAddRecord(adbk, personRecord, &error) | |
if couldAddPerson{ | |
print("Successfully added the person") | |
} else { | |
print("Failed to add the person.") | |
return | |
} | |
self.addPersonToGroup(personRecord) | |
} | |
func getPersonRecord(first: String, last: String, phone : String, allContacts : [ABRecordRef]) -> ABRecordRef? { | |
if !self.determineStatus() { | |
print("not authorized") | |
return nil | |
} | |
//let allContacts = ABAddressBookCopyArrayOfAllPeople(adbk).takeRetainedValue() as Array | |
var personContact: ABRecordRef? | |
for record in allContacts { | |
let currentContact: ABRecordRef = record | |
var firstName : String = "" | |
var lastName : String = "" | |
if let contactFirstName = ABRecordCopyValue(currentContact, kABPersonFirstNameProperty)?.takeRetainedValue() as? String | |
{ | |
//print ("\t\t contactFirstName : \(contactFirstName)") | |
firstName = contactFirstName | |
} | |
if let contactLastName = ABRecordCopyValue(currentContact, kABPersonLastNameProperty)?.takeRetainedValue() as? String | |
{ | |
//print ("\t\t contactLastName : \(contactLastName)") | |
lastName = contactLastName | |
} | |
var phoneExists : Bool = false | |
let phones: ABMultiValueRef = ABRecordCopyValue(currentContact,kABPersonPhoneProperty).takeRetainedValue() as ABMultiValueRef | |
if ABMultiValueGetCount(phones) > 0 { | |
for var i:Int = 0; i < ABMultiValueGetCount(phones); i++ { | |
var value: String = "" | |
if let phoneNumber = ABMultiValueCopyValueAtIndex(phones, i)?.takeRetainedValue() as? String | |
{ | |
value = phoneNumber | |
let components = value.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) | |
let decimalContactPhone = "".join(components) as String | |
let componentsPhones = phone.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) | |
let decimalPhone = "".join(componentsPhones) as String | |
print(decimalContactPhone) | |
print(decimalPhone) | |
if decimalPhone.rangeOfString(decimalContactPhone) != nil | |
{ | |
phoneExists = true | |
break | |
} | |
} | |
} | |
} | |
print(first) | |
print(last) | |
if (firstName.lowercaseString == first.lowercaseString && lastName.lowercaseString == last.lowercaseString && phoneExists) { | |
print("found \(first) \(last).") | |
personContact = currentContact | |
return personContact | |
} | |
} | |
return personContact | |
} | |
func saveAddressBookChanges() { | |
if ABAddressBookHasUnsavedChanges(adbk){ | |
var err: Unmanaged<CFErrorRef>? = nil | |
let savedToAddressBook = ABAddressBookSave(adbk, &err) | |
if savedToAddressBook { | |
print("Successully saved changes.") | |
} else { | |
print("Couldn't save changes.") | |
} | |
} else { | |
print("No changes occurred.") | |
} | |
} | |
func getContacts() -> [NSDictionary]? { | |
if !self.determineStatus() { | |
print("not authorized") | |
return nil | |
} | |
var contactsArray : [NSDictionary] = [] | |
let people = ABAddressBookCopyArrayOfAllPeople(adbk).takeRetainedValue() as NSArray as [ABRecord] | |
for record:ABRecordRef in people { | |
let contactPerson: ABRecordRef = record | |
let phones: ABMultiValueRef = ABRecordCopyValue(contactPerson,kABPersonPhoneProperty).takeRetainedValue() as ABMultiValueRef | |
var phonesArray = Array<Dictionary<String,String>>() | |
if ABMultiValueGetCount(phones) > 0 { | |
for var i:Int = 0; i < ABMultiValueGetCount(phones); i++ { | |
var label: String = "" | |
var value: String = "" | |
if let phoneLabel = ABMultiValueCopyLabelAtIndex(phones, i)?.takeRetainedValue() as? String | |
{ | |
label = phoneLabel | |
} | |
if let phoneNumber = ABMultiValueCopyValueAtIndex(phones, i)?.takeRetainedValue() as? String | |
{ | |
value = phoneNumber | |
} | |
print("Phone: \(label) = \(value)") | |
let phone = ["label" : label, "phone" : value] | |
phonesArray.append(phone) | |
} | |
} | |
else | |
{ | |
continue | |
} | |
var emailsArray = Array<Dictionary<String,String>>() | |
let emailsRef: ABMultiValueRef = ABRecordCopyValue(contactPerson, kABPersonEmailProperty).takeRetainedValue() as ABMultiValueRef | |
if ABMultiValueGetCount(emailsRef) > 0 { | |
for var i:Int = 0; i < ABMultiValueGetCount(emailsRef); i++ { | |
var label: String = "" | |
var value: String = "" | |
if let phoneLabel = ABMultiValueCopyLabelAtIndex(emailsRef, i)?.takeRetainedValue() as? String | |
{ | |
label = phoneLabel | |
} | |
if let phoneNumber = ABMultiValueCopyValueAtIndex(emailsRef, i)?.takeRetainedValue() as? String | |
{ | |
value = phoneNumber | |
} | |
print("Phone: \(label) = \(value)") | |
let email = ["label" : label, "email" : value] | |
emailsArray.append(email) | |
} | |
} | |
//var nickName : String = "" | |
var firstName : String = "" | |
var lastName : String = "" | |
/*if let contactNickname = ABRecordCopyValue(contactPerson, kABPersonNicknameProperty)?.takeRetainedValue() as? String | |
{ | |
print ("\t\t contactNickname : \(contactNickname)") | |
nickName = contactNickname | |
}*/ | |
if let contactFirstName = ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty)?.takeRetainedValue() as? String | |
{ | |
print ("\t\t contactFirstName : \(contactFirstName)") | |
firstName = contactFirstName | |
} | |
if let contactLastName = ABRecordCopyValue(contactPerson, kABPersonLastNameProperty)?.takeRetainedValue() as? String | |
{ | |
print ("\t\t contactLastName : \(contactLastName)") | |
lastName = contactLastName | |
} | |
let person = ["firstname": firstName, "lastname": lastName, "phones" : phonesArray, "emails" : emailsArray] | |
contactsArray.append(person) | |
} | |
print("contacts count \(contactsArray.count)") | |
return contactsArray | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment