我是Swift的新手。从iPhone导出联系人并将其转换为.Vcf文件以便将文件上传到Web服务器时遇到问题。此外,我想从Web服务器导入.Vcf文件并将其转换为iPhone联系人的模式。谁能帮我达到预期的效果吗?。
答案 0 :(得分:5)
请尝试以下代码段。
public func processContacts() throws {
let contactStore = CNContactStore()
let status = CNContactStore.authorizationStatus(for: .contacts)
switch status {
case .denied:
throw ContactAccessError(description: "Access Denied")
case .notDetermined:
// In case of not determined request for access
// If allowed it will return success otherwise return error
contactStore.requestAccess(for: .contacts, completionHandler:{ success, error in
if success {
print("Access Allowed")
var contacts = [CNContact]()
let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey as NSString, CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])
do {
try contactStore.enumerateContacts(with: request) { contact, stop in
contacts.append(contact)
}
} catch {
print(error)
}
for contact in contacts{
do{
var data = Data()
try data = CNContactVCardSerialization.data(with: [contact])
let fileManager = FileManager.default
do {
let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
let fileURL = documentDirectory.appendingPathComponent("someName").appendingPathExtension("vcf")
try data.write(to: fileURL)
} catch {
print(error)
}
}catch{
print("Some Error")
}
}
}
})
default:
break
}
}
class ContactAccessError: LocalizedError {
private var desc = ""
init(description: String) {
desc = description
}
var errorDescription: String? {
get {
return self.desc
}
}
}