I want to choose iPhone contacts in contacts application, generate .vcf file, write chosen contacts in this file and send to server.
As I know in iOS 9 many functions of address book are depreciated, so can anybody help me to write this code in a correct way.
The general pieces you will need are:
CNContact
data to VCard format.Below is an example which answers the question of saving a contact to VCard format.
import Contacts
// Creating a mutable object to add to the contact
let contact = CNMutableContact()
contact.imageData = NSData() // The profile picture as a NSData object
contact.givenName = "John"
contact.familyName = "Appleseed"
let homeEmail = CNLabeledValue(label:CNLabelHome, value:"[email protected]")
let workEmail = CNLabeledValue(label:CNLabelWork, value:"[email protected]")
contact.emailAddresses = [homeEmail, workEmail]
contact.phoneNumbers = [CNLabeledValue(
label:CNLabelPhoneNumberiPhone,
value:CNPhoneNumber(stringValue:"(408) 555-0126"))]
let homeAddress = CNMutablePostalAddress()
homeAddress.street = "1 Infinite Loop"
homeAddress.city = "Cupertino"
homeAddress.state = "CA"
homeAddress.postalCode = "95014"
contact.postalAddresses = [CNLabeledValue(label:CNLabelHome, value:homeAddress)]
let birthday = NSDateComponents()
birthday.day = 1
birthday.month = 4
birthday.year = 1988 // You can omit the year value for a yearless birthday
contact.birthday = birthday
let data = try CNContactVCardSerialization.dataWithContacts([contact])
let s = String(data: data, encoding: NSUTF8StringEncoding)
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first {
let fileURL = directoryURL.URLByAppendingPathComponent("john.appleseed").URLByAppendingPathExtension("vcf")
try data.writeToURL(fileURL, options: [.AtomicWrite])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With