Skip to content

Instantly share code, notes, and snippets.

@sooop
Last active October 7, 2015 05:33
Show Gist options
  • Select an option

  • Save sooop/ab5e6118ee52cdc32bef to your computer and use it in GitHub Desktop.

Select an option

Save sooop/ab5e6118ee52cdc32bef to your computer and use it in GitHub Desktop.
import Contacts
func update()
{
func makeNickname(name: String) -> String
{
let transform: UnicodeScalar -> String = { u in
let c = Int(u.value)
guard case 0xac00...0xd7a3 = c else { return "" }
return String(UnicodeScalar((c - 0xac00) / 28 / 21 + 0x1100))
}
let result = name.unicodeScalars.map(transform).joinWithSeparator("")
return result
}
let store = CNContactStore()
let fetchRequest = CNContactFetchRequest(keysToFetch:[CNContactGivenNameKey,
CNContactNicknameKey])
let saveRequest = CNSaveRequest()
do {
try store.enumerateContactsWithFetchRequest(fetchRequest){ contact, stop in
let name = contact.givenName
let nickname = makeNickname(name)
guard nickname.utf8.count > 0 && nickname != contact.nickname else { return }
let mutableContact = contact.mutableCopy() as! CNMutableContact
mutableContact.nickname = nickname
saveRequest.updateContact(mutableContact)
}
} catch {
print("An error occurred during fetching contact information.")
}
do {
try store.executeSaveRequest(saveRequest)
} catch {
print("An error occurred during saving contacts.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment