iOS9 联系人框架从新保存的联系人中获取标识符

标签 ios swift cncontact cncontactstore contacts-framework

在保存请求之后,我需要一个新创建的联系人的标识符。用例:在我的应用程序中,用户创建了一个新联系人并为他们提供了一些属性(例如姓名、地址......),之后他可以保存联系人。此场景按方面工作。我的代码如下所示:

    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)
       }
  }

联系人对象 (uiContact) 只是 CNContact 的包装器。 在关闭完成时我需要返回标识符,但此时我无法访问它们,因为他是在写入过程之后由系统创建的。 一种解决方案是使用谓词获取新保存的 CNContact

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

但这在我看来有点不干净,因为这个联系人可能只有一个名字,但可能存在多个。像带有创建的标识符的回调之类的东西会很好。但是没有。 有没有其他方法可以解决这个问题?

最佳答案

这可能有点晚,但以防万一有人需要。

通过使用最新的 SDK (iOS 11),我能够通过以下方式获取标识符:

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");
    }
}

关于iOS9 联系人框架从新保存的联系人中获取标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37896051/

相关文章:

ios - 如何直接打开新联系人屏幕?

ios - 如何在 Interstitial 被解散之前释放场景?

swift - 如何在 swift 中正确创建多维数组?

ios - 在 UIViewController 中管理方向的说明

ios - 无法将 Action 设置为在 Storyboard 上创建的 UIBarButtonItem

ios - CNContactPickerViewController 仅检索选定的项目

ios - CNContacts -- 地址行 2

iphone - 在 APP 购买服务器模型中,我首先放置免费应用程序,然后通过订阅提供不同的模块,这是否可能?

java - 初始化二维数组

ios - ASP.NET存储过程调用将VarBinary插入sql