Last active
November 27, 2015 11:02
-
-
Save McNight/19b407e25de996b7a2ad to your computer and use it in GitHub Desktop.
Uppercase all contacts family names
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
// A Twitter guy requested a way to update all his contacts family names to be uppercased | |
// So, I wanted to give a try to the all new iOS 9 Contacts framework | |
// I'm a Swift noob, I didn't even finish reading the Swift book (I'm at p. 302 :D) | |
import Contacts | |
let store = CNContactStore() | |
store.requestAccessForEntityType(.Contacts) { success, formerError in | |
if success | |
{ | |
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { | |
let predicate = CNContact.predicateForContactsInContainerWithIdentifier(store.defaultContainerIdentifier()) | |
let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey] | |
do { | |
let contacts = try store.unifiedContactsMatchingPredicate(predicate, keysToFetch: keysToFetch) | |
let saveRequest = CNSaveRequest() | |
for contact in contacts { | |
if (contact.isKeyAvailable(CNContactFamilyNameKey)) { | |
let updatedContact: CNMutableContact = contact.mutableCopy() as! CNMutableContact | |
updatedContact.familyName = contact.familyName.uppercaseString | |
saveRequest.updateContact(updatedContact) | |
} | |
} | |
try store.executeSaveRequest(saveRequest) | |
} catch _ { | |
print("An error occured.") | |
} | |
} | |
} | |
else | |
{ | |
if let error = formerError { | |
print(error.localizedDescription) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@fgringo: Sorry for taking so long to answer (I didn't receive any notification...), anyway...
It worked perfectly for me : I do get all the contacts if I put this snippet inside a simple application.
Maybe you have a very specific way to handle the contacts with your phone. Try looking at the CNContactStore and CNContainer documentation !