现在,当我打开通讯录时,首先打开模式,其中包含我在通讯录表单中添加的最后一个号码,该号码是从我的应用程序添加的
这是我的代码:
[self updateRecord:contact withData:contactData];
CNContactViewController *controller = [CNContactViewController viewControllerForNewContact:contact];
controller.delegate = self;
dispatch_async(dispatch_get_main_queue(), ^{
UINavigationController* navigation = [[UINavigationController alloc] initWithRootViewController:controller];
UIViewController *viewController = (UIViewController*)[[[[UIApplication sharedApplication] delegate] window] rootViewController];
while (viewController.presentedViewController)
{
viewController = viewController.presentedViewController;
}
[viewController presentViewController:navigation animated:YES completion:nil];
self->updateContactPromise = resolve;
下面是委托方法代码:
[viewController dismissViewControllerAnimated:YES completion:nil];
if(updateContactPromise) {
if (contact) {
NSDictionary *contactDict = [self contactToDictionary:contact withThumbnails:true];
updateContactPromise(contactDict);
} else {
updateContactPromise(nil);
}
updateContactPromise = nil;
}
}
我刚刚看到这篇文章,据我了解,应该避免在通过CNContactViewController取消创建新联系人后,在iPhone上打开联系人应用程序时仍然存在未保存的草稿。我发现,如果 CNMutableContact 首先以读取模式打开,然后通过 contactViewController.allowsEditing = true 设置为更改,并且 contactViewController.setEditing(true,animated: true) 正在做的技巧是避免地址簿中未保存的草稿。
我用 Xcode 16.1 for iOS 18.1 和 SWIFT 6 解决了这个问题。
struct ContactViewControllerRepresentable: UIViewControllerRepresentable {
private var contact = CNMutableContact()
func makeCoordinator() -> Coordinator {
return Coordinator()
}
func makeUIViewController(context: Context) -> UINavigationController {
let contactViewController = CNContactViewController(for: contact)
contactViewController.allowsEditing = true
contactViewController.setEditing(true, animated: true)
contactViewController.delegate = context.coordinator
self.contact.givenName = "John"
self.contact.familyName = "Doe"
self.contact.phoneNumbers = [CNLabeledValue(
label: CNLabelPhoneNumberMobile,
value: CNPhoneNumber(stringValue: "123-456-7890")
)]
self.contact.emailAddresses = [CNLabeledValue(
label: CNLabelWork,
value: "[email protected]" as NSString
)]
let navigationController = UINavigationController(rootViewController: contactViewController)
navigationController.delegate = context.coordinator
return navigationController
}
func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {
}
}
class Coordinator: NSObject, @preconcurrency CNContactViewControllerDelegate, UINavigationControllerDelegate {
func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) {
viewController.dismiss(animated: true, completion: nil)
}
}