ios - Export iPhone contacts to .vcf file programatically -
i want choose iphone contacts in contacts application, generate .vcf file, write chosen contacts in file , send server.
as know in ios 9 many functions of address book depreciated, can me write code in correct way.
the general pieces need are:
- the contacts framework accessing phone's contacts.
- the contactsui framework use built-in view controllers accessing contacts.
- use cncontactvcardserialization.datawithcontacts encode
cncontact
data vcard format. - write data file using data.writetourl.
- upload data server using nsurlsession.
below example answers question of saving contact vcard format.
import contacts // creating mutable object add contact let contact = cnmutablecontact() contact.imagedata = nsdata() // profile picture nsdata object contact.givenname = "john" contact.familyname = "appleseed" let homeemail = cnlabeledvalue(label:cnlabelhome, value:"john@example.com") let workemail = cnlabeledvalue(label:cnlabelwork, value:"j.appleseed@icloud.com") 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 // can omit year value 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]) }
Comments
Post a Comment