Created
December 14, 2014 05:01
-
-
Save samuelbeek/474aa8c18bb6891d835f to your computer and use it in GitHub Desktop.
Add contact to address book in swift
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
func addUserToAddressBook(contact: User){ | |
let stat = ABAddressBookGetAuthorizationStatus() | |
switch stat { | |
case .Denied, .Restricted: | |
println("no access to addressbook") | |
case .Authorized, .NotDetermined: | |
var err : Unmanaged<CFError>? = nil | |
var adbk : ABAddressBook? = ABAddressBookCreateWithOptions(nil, &err).takeRetainedValue() | |
if adbk == nil { | |
println(err) | |
return | |
} | |
ABAddressBookRequestAccessWithCompletion(adbk) { | |
(granted:Bool, err:CFError!) in | |
if granted { | |
var newContact:ABRecordRef! = ABPersonCreate().takeRetainedValue() | |
var success:Bool = false | |
//Updated to work in Xcode 6.1 | |
var error: Unmanaged<CFErrorRef>? = nil | |
//Updated to error to &error so the code builds in Xcode 6.1 | |
success = ABRecordSetValue(newContact, kABPersonFirstNameProperty, contact.name, &error) | |
println("Setting first name was successful? \(success)") | |
success = ABRecordSetValue(newContact, kABPersonLastNameProperty, "", &error) | |
println("Setting last name was successful? \(success)") | |
success = ABRecordSetValue(newContact, kABPersonJobTitleProperty, contact.jobTitle, &error) | |
println("Setting job title was successful? \(success)") | |
if(contact.phoneNumber != nil) { | |
let propertyType: NSNumber = kABMultiStringPropertyType | |
var phoneNumbers: ABMutableMultiValueRef = createMultiStringRef() | |
var phone = ((contact.phoneNumber as String).stringByReplacingOccurrencesOfString(" ", withString: "") as NSString) | |
ABMultiValueAddValueAndLabel(phoneNumbers, phone, kABPersonPhoneMainLabel, nil) | |
success = ABRecordSetValue(newContact, kABPersonPhoneProperty, phoneNumbers, &error) | |
println("Setting phone number was successful? \(success)") | |
} | |
success = ABRecordSetValue(newContact, kABPersonNoteProperty, "added via wildcard - getwildcard.co", &error) | |
success = ABAddressBookAddRecord(adbk, newContact, &error) | |
println("Contact added successful? \(success)") | |
success = ABAddressBookSave(adbk, &error) | |
println("Saving addressbook successful? \(success)") | |
} else { | |
println(err) | |
} | |
} | |
} | |
func createMultiStringRef() -> ABMutableMultiValueRef { | |
let propertyType: NSNumber = kABMultiStringPropertyType | |
return Unmanaged.fromOpaque(ABMultiValueCreateMutable(propertyType.unsignedIntValue).toOpaque()).takeUnretainedValue() as NSObject as ABMultiValueRef | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thxs You,
Can you explain me - contact: User?