Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS9 Contacts Framework get identifier from newly saved contact

I need the identifier of a newly created contact directly after the save request. The use case: Within my app a user creates a new contact and give them some attributes (eg. name, address ...) after that he can save the contact. This scenario is working as aspected. My code looks like this:

    func createContact(uiContact: Contact, withImage image:UIImage?, completion: String -> Void)
    {    
       let contactToSave = uiContact.mapToCNContact(CNContact()) as! Cnmutablecontawctlet
       if let newImage = image
       {
          contactToSave.imageData = UIImageJPEGRepresentation(newImage, 1.0)
       }
       request           = CNSaveRequest()
       request.addContact(contactToSave, toContainerWithIdentifier: nil)
       do
       {
          try self.contactStore.executeSaveRequest(request)
          print("Successfully saved the CNContact")
          completion(contactToSave.identifier)
       }
       catch let error
       {
         print("CNContact saving faild: \(error)")
         completion(nil)
       }
  }

The Contact Object (uiContact) is just an wrapper of CNContact. In the closure completion I need to return the identifier but on this time I have no access to them, because he is creating by the system after the write process. One solution could be to fetch the newly saved CNContact with predicate

public func unifiedContactsMatchingPredicate(predicate: NSPredicate, keysToFetch keys: [CNKeyDescriptor]) throws -> [CNContact]

but this seems to me like a bit unclean because this contact could have only a name and more than one could exist. Something like a callback with the created identifier would be nice. But there isn´t. Is there a other way to solve this problem?

like image 810
Thomas G. Avatar asked Jun 18 '16 10:06

Thomas G.


1 Answers

This may be a little late but in case someone needs this.

By using the latest SDK (iOS 11), I was able to get the identifier just by:

NSError *error = nil;

saveReq = [[CNSaveRequest alloc] init];
[saveReq addContact:cnContact toContainerWithIdentifier:containerIdentifier];

if (![contactStore executeSaveRequest:saveReq error:&error]) {
    NSLog(@"Failed to save, error: %@", error.localizedDescription);
}
else
{
    if ([cnContact isKeyAvailable:CNContactIdentifierKey]) {
        NSLog(@"identifier for new contact is: %@", cnContact.identifier);
        // this works for me everytime
    } else {
        NSLog(@"CNContact identifier still isn't available after saving to address book");
    }
}
like image 101
Yufei L. Avatar answered Sep 18 '22 14:09

Yufei L.