ios - 如何在 iOS 上获取联系人并存储在数组中?

标签 ios swift delegates cncontactstore

我正在开发适用于 iOS 联系人的 Tinder 滑动应用程序。我已导入联系人库并成功在控制台中打印联系人。但是,我正在尝试将这些名称动态添加到 Tinder 等卡片中。我已经创建了一个模型类来保存该名称,但是,我无法将我的数据附加到该模型。

    struct ContactInfo {

    var name: String

}


  let contactInfo = [ContactInfo]()
    func fetchContacts(){
        let contactStore = CNContactStore()
        var contacts = [CNContact]()
        let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]
        let request = CNContactFetchRequest(keysToFetch: keys)

        do {
            try contactStore.enumerateContacts(with: request) { (contact, stop) in
                contacts.append(contact)
                var info = contact.givenName + " " + contact.familyName
                print(info)

            }
        } catch {
            print(error.localizedDescription)
        }

    }
    var userModels : [ContactInfo] =  {
        var model : [ContactInfo] = []
        for n in 1...10 {
            model.append(ContactInfo(name: names[Int(arc4random_uniform(UInt32(names.count)))]))
        }
        return model
    }()

我希望我的所有联系人都附加到模型变量中,然后将其返回到卡片中。

最佳答案

据我了解,enumerateContacts 是异步的。这意味着,当您的应用执行创建 userModels 数组的行时,尚未获取联系人:因此您的数组保持为空。

我会尝试将 userModels 数组创建移动到另一个 Controller 中,您将在其中显示卡片。

为此,您可以使用委托(delegate),该委托(delegate)接收获取的联系人作为参数。然后,您可以使用此参数内容分配数组并创建卡片内容。

这是一个great tutorial on how to use a delegate with Swift .

希望这对您有帮助。

关于ios - 如何在 iOS 上获取联系人并存储在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56248035/

相关文章:

ios - 是否可以在构建已获准进行测试时上传新构建以供试飞审查?

swift - 每次调用时使用 func 来替代任务 a 或 b

ios - 'UIViewController' 没有可见的 @interface 声明选择器

ios - 在 Objective C 中使用双工(双向)委托(delegate)

ios - 如何重构对象数组

ios - iCarousel 数据源问题

swift - 快速访问表格 View 中的每个标题和控件

ios - UIImageView:如何显示缩放图像?

iphone - 访问委托(delegate)中的局部变量的正确方法是什么?

ios - EXC_BAD_ACCESS 与 UIBarButtonItem appearanceWhenContainedIn 在 iOS 7