Search code examples
iosswiftmacoscontactscncontact

Custom labels associated with a contact IOS OS X Contact Framework Swift


How do I access the read-only and/or mutable contact records pertaining to what I believe to be custom labeled relationship contact data?

For instance I have Daughter-In-Law, Husband or Son custom labels associated with a contact Do I need CNLabeledValue CNLabelContactRelationChild? What do I need to read these or get these custom labels from contact data?


Solution

  • Here is what I managed to do in order to assign a relation to a contact and be able to fetch it using the relation

    var myNewContact = CNMutableContact()
    let myRelation = CNContactRelation(name: "mommy")
    let myMom = CNLabeledValue(label: CNLabelContactRelationMother, value: myRelation)
     myNewContact.contactRelations.append(myMom)
    
    // add additional info to your contact such as name, email, family
    // save your contact
    
    let keysToFetch = [CNContactGivenNameKey, CNContactRelationsKey, CNContactEmailAddressesKey]    
    let text =  "mommy"
        let request = CNContactFetchRequest(keysToFetch: keysToFetch)
            do {
                try store.enumerateContactsWithFetchRequest(request) {
                    contact, stop in
                    for var i = 0; i < contact.contactRelations.count; i++ {
                        if (contact.contactRelations[i].valueForKey("value")?.valueForKey("name")!)! as? String == text
                        {
                        print(contact.givenName)
                        print(contact.identifier)
                       }
                    }
                }
            } catch let err{
                print(err)
            }
        }