1

在我的应用程序中,我创建了一个 CNContact 并保存到联系人商店,我还保存了联系人的标识符。在应用程序的另一部分中,我使用标识符来获取该联系人,但在 iOS 13中不起作用。(这在 iOS 12 上有效

注意:我知道 iOS 13 上的联系人备注密钥权限,但我没有获取该字段。

以下是我创建联系人的方式:

func createPlaceholderContactFor(telephoneNumber: String) {
    guard
        placeholderContactIdentifier == nil,
        CNContactStore.authorizationStatus(for: .contacts) == .authorized
    else {
        return
    }

    // Creating a mutable object to add to the contact
    let contact = CNMutableContact()
    contact.imageData = UIImage(named: "MainIcon")?.jpegData(compressionQuality: 1.0)
    contact.givenName = placeholderDefaultName
    contact.familyName = ""
    contact.phoneNumbers = [CNLabeledValue(
        label:CNLabelPhoneNumberiPhone,
        value:CNPhoneNumber(stringValue:telephoneNumber))]

    // Saving the newly created contact
    let saveRequest = CNSaveRequest()
    saveRequest.add(contact, toContainerWithIdentifier:nil)

    do {
        let store = CNContactStore()
        try store.execute(saveRequest)

        if contact.isKeyAvailable(CNContactIdentifierKey) {
            print(contact.identifier) //this is printed on console and contact appears on phone app.
            placeholderContactIdentifier = contact.identifier
        }
    } catch {
        print(error.localizedDescription)
    }
}

这就是我获取联系人的方式:

private func placeholderContact() -> CNContact? {
    guard
        let identifier = placeholderContactIdentifier,
        CNContactStore.authorizationStatus(for: .contacts) == .authorized
        else { return nil }

    let predicate: NSPredicate = CNContact.predicateForContacts(withIdentifiers: [identifier])

    let keysToFetch = [
        CNContactIdentifierKey as CNKeyDescriptor,
        CNContactGivenNameKey as CNKeyDescriptor,
        CNContactFamilyNameKey as CNKeyDescriptor,
        CNContactPhoneNumbersKey as CNKeyDescriptor
    ]

    do {
        let store = CNContactStore()

        let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keysToFetch)
        return contacts.first
    }
    catch {
        print(error.localizedDescription)

        return nil
    }
}

我也尝试过使用let contact = try store.unifiedContact(withIdentifier: identifier, keysToFetch: keysToFetch)而不是,let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keysToFetch)但这会引发错误。

4

0 回答 0