32 lines
1.0 KiB
Swift
32 lines
1.0 KiB
Swift
import Contacts
|
|
|
|
/// Service for saving vCard data to the user's Contacts.
|
|
struct ContactSaveService: Sendable {
|
|
|
|
/// Saves the vCard data as a new contact.
|
|
/// - Parameter vCardData: The vCard string to parse and save.
|
|
func saveContact(vCardData: String) async throws {
|
|
let store = CNContactStore()
|
|
|
|
let authorized = try await store.requestAccess(for: .contacts)
|
|
guard authorized else {
|
|
throw ClipError.contactsAccessDenied
|
|
}
|
|
|
|
guard let data = vCardData.data(using: .utf8),
|
|
let contact = try CNContactVCardSerialization.contacts(with: data).first else {
|
|
throw ClipError.invalidRecord
|
|
}
|
|
|
|
let mutableContact = contact.mutableCopy() as? CNMutableContact ?? CNMutableContact()
|
|
let saveRequest = CNSaveRequest()
|
|
saveRequest.add(mutableContact, toContainerWithIdentifier: nil)
|
|
|
|
do {
|
|
try store.execute(saveRequest)
|
|
} catch {
|
|
throw ClipError.contactSaveFailed
|
|
}
|
|
}
|
|
}
|