我正在开发适用于 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/