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