SwiftUI x ContactsUI,将联系人添加到群组

5 swift cncontactstore swiftui

首先,对不起我的英语,我不是母语人士。如果有任何不清楚的地方,请告诉我。

在我的项目中,有一个部分供用户组织联系人,但仅限于特定的联系人组。我可以为联系人实现自定义结构或类,但苹果的联系人框架几乎是完美的。我还想使用设备的通话、短信和电子邮件功能。

所以我将 ContactsUI 实现到我的 SwiftUI 应用程序中:

struct addContactUIView : UIViewControllerRepresentable {
    func makeCoordinator() -> Coordinator {
        return Coordinator(self)
    }

    class Coordinator: NSObject, CNContactViewControllerDelegate, UINavigationControllerDelegate {

        private func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNMutableContact?) {
            if let c = contact {
                self.parent.contact = c
            }
            viewController.dismiss(animated: true)
        }
    
        func contactViewController(_ viewController: CNContactViewController, shouldPerformDefaultActionFor property: CNContactProperty) -> Bool {
            return true
        }

        var parent: addContactUIView

        init(_ parent: addContactUIView) {
            self.parent = parent
        }
    }

    @Binding var contact: CNMutableContact

    init(contact: Binding<CNMutableContact>) {
        self._contact = contact
    }

    typealias UIViewControllerType = CNContactViewController
   
    func makeUIViewController(context: UIViewControllerRepresentableContext<addContactUIView>) -> addContactUIView.UIViewControllerType {
        let viewController = CNContactViewController(forNewContact: CNContact())
        viewController.delegate = context.coordinator
        return viewController
    }

    func updateUIViewController(_ uiViewController: addContactUIView.UIViewControllerType, context: UIViewControllerRepresentableContext<addContactUIView>) {
    
    }
}
Run Code Online (Sandbox Code Playgroud)

ContactsUI 框架为我提供了默认的保存和编辑选项,这真的很棒。

问题是:如何将新联系人添加到联系人中的特定组?例如“客户”。有一个“addMember”函数可以实现此目的,但是我应该在哪里实现它?

我被困在这里,所以我非常感谢任何帮助!