Skip to content

Instantly share code, notes, and snippets.

@McNight
Last active November 27, 2015 11:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save McNight/19b407e25de996b7a2ad to your computer and use it in GitHub Desktop.
Save McNight/19b407e25de996b7a2ad to your computer and use it in GitHub Desktop.
Uppercase all contacts family names
// 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)
}
}
}
@csfelipe
Copy link

csfelipe commented Nov 5, 2015

Thanks, mate. Where you able to find a way to get all the contacts? With this one just a few came (which is better from all the posts I've seen in the past hour)

@McNight
Copy link
Author

McNight commented Nov 27, 2015

@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 !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment