Last active
October 7, 2015 05:33
-
-
Save sooop/ab5e6118ee52cdc32bef to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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