Last active
May 16, 2024 18:37
-
-
Save gazolla/33a52135c071d8cadcf174aa194ee2cc to your computer and use it in GitHub Desktop.
How to create a Contact programmatically using swift 3 for iOS
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
import Contacts | |
func createContact()->CNMutableContact{ | |
let contact = CNMutableContact() | |
contact.namePrefix = "John" | |
contact.nameSuffix = "Applesee" | |
contact.organizationName = "Apple" | |
contact.jobTitle = "Software Engineer" | |
let dateFormatter = DateFormatter() | |
dateFormatter.locale = Locale.current | |
dateFormatter.dateStyle = DateFormatter.Style.medium | |
let birthday = dateFormatter.date(from: "20/10/1995") | |
let birthdayComponents = Calendar.current.dateComponents([.year, .month, .day], from: birthday!) | |
contact.birthday = birthdayComponents | |
let phone = CNLabeledValue( | |
label:CNLabelPhoneNumberMain, | |
value:CNPhoneNumber(stringValue:"555-5555")) | |
let mobileNumber = CNLabeledValue( | |
label:CNLabelPhoneNumberMobile, | |
value:CNPhoneNumber(stringValue:"999-9999") | |
contact.phoneNumbers = [phone, mobileNumber] | |
let WorkEmail = CNLabeledValue(label:CNLabelWork, value: "[email protected]") | |
contact.emailAddresses = [WorkEmail] | |
let address = CNMutablePostalAddress() | |
address.street = "Infinity Loop" | |
address.city = "Cupertino' | |
address.state = "CA" | |
address.postalCode = "95014" | |
address.country = "United States" | |
let labeledAddress = CNLabeledValue<CNPostalAddress>(label: CNLabelHome, value: address) | |
contact.postalAddresses = [labeledAddress] | |
return contact | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The code above is great. I am using swift 4 and I had a tiny problem with the date. It gave an error when I run it saying unexpectedly found nil while unwrapping. I fixed it using dateFormatter.dateFormat = "dd-MM-yyyy". After adding this line the birthday property wasn't nil. I don't know if swift 3 or below would give the same problem.