【问题标题】:iOS9 Contacts Framework get identifier from newly saved contactiOS9 Contacts Framework 从新保存的联系人中获取标识符
【发布时间】:2016-10-20 03:31:08
【问题描述】:

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

    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]

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

【问题讨论】:

    标签: ios swift cncontact cncontactstore contacts-framework


    【解决方案1】:

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

    通过使用最新的 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");
        }
    }
    

    【讨论】:

      【解决方案2】:

      斯威夫特 4

      这是创建联系人时获取联系人id的方式

          do {
              try store.execute(saveRequest)
              if contactToAdd.isKeyAvailable(CNContactIdentifierKey) {
                  print(contactToAdd.identifier) // here you are getting identifire
              }
          }
          catch {
              print(error)
          }
      

      【讨论】:

      • 也适用于 swift 5
      • 这对我不起作用,因为我在将联系人保存到 Google 通讯录时发现,我保存的标识符在保存后似乎发生了变化。令人讨厌的是,这意味着如果我将联系人添加到组中,当我重新获取该组时它会消失,因为它不再存在。但是,现在可以在地址簿中找到新创建的联系人,但标识符不同,我可以将其添加到组中。我很困惑为什么
      • 当时它对我有用,在这个阶段我也为这个功能疯狂。感谢您来到这里,请在收到后提供您的答案。
      猜你喜欢
      • 2012-08-24
      • 2014-08-15
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 2019-04-04
      • 2014-01-10
      • 1970-01-01
      • 2016-06-06
      相关资源
      最近更新 更多