如何从设备创建所有联系人的.xml文件。或如何将.vcf文件导入.xml文件

时间:2019-04-03 18:45:50

标签: swift xml

我想为ios设备的所有联系人创建一个.xml文件,然后在另一端再次发送该文件,我想解析xml并创建联系人,请注意:-可以使用.vcf作为中介,但是为此项目,我必须创建.xml文件。

2 个答案:

答案 0 :(得分:0)

我通过编写单独的Reader和Writer解决了这个问题: 读者功能:-

     func contactsToVCARDXMLGenerator()-> AEXMLDocument{

    let store = CNContactStore()
    var contacts : [CNContact] = []
    let contactsXML = AEXMLDocument()
    let root = contactsXML.addChild(name: "root")
    let fetchRequest = CNContactFetchRequest(keysToFetch:[CNContactVCardSerialization.descriptorForRequiredKeys()])
    do {
        try store.enumerateContacts(with: fetchRequest, usingBlock: { (contact, stop) -> Void in
            contacts.append(contact)
        })
    }
    catch{
        print(error.localizedDescription)
    }
    do {
        let vcarddat = try CNContactVCardSerialization.data(with: contacts)
        let vcardAsString = String(data: vcarddat, encoding: .utf8)
        print(vcardAsString!)
        let contactsArray = vcardAsString!.components(separatedBy: "END:VCARD")
        for index in 0..<contacts.count {
            root.addChild(name: "contact", value: "\(contactsArray[index])")
        }
    }catch{
        print(error.localizedDescription)
    }
    return contactsXML
}

答案 1 :(得分:0)

 func xmlToRemindersEntries(xmlDoc : String) -> Bool{
    //print(xmlDoc)
    do{
        let doc = try AEXMLDocument.init(xml: xmlDoc)
        var vcardString = String()
        for contact in doc.root.children {
            vcardString += "\(contact.value!)\nEND:VCARD\n"
        }
        let contacts = try CNContactVCardSerialization.contacts(with: vcardString.data(using: .utf8)!)
        for each in contacts{
            let mutCpoy = each.mutableCopy() as! CNMutableContact
            let store = CNContactStore()
            let saveRequest = CNSaveRequest()
            saveRequest.add(mutCpoy, toContainerWithIdentifier:nil)
            try! store.execute(saveRequest)
        }

    }catch{
        print(error.localizedDescription)
        return false
    }
   return true
}