ios - 如何在 TableView 中显示 APAddressBook 的联系人

标签 ios swift abaddressbook

我需要一些使用 APAddressBook 的帮助。

我无法理解如何使用 APAddressBook 加载和显示联系人。

我认为这个函数会获取地址簿中的所有联系人

func loadContacts() {
    self.addressBook.loadContacts({
        (contacts: [APContact]?, error: NSError?) in
        if let unwrappedContacts = contacts {
            print(unwrappedContacts)

        } else {
            // show error...

这个函数提取名字

func contactName(contact :APContact) -> String {
    if let firstName = contact.name?.firstName, lastName = contact.name?.lastName {
        return "\(firstName) \(lastName)"
    }
    else if let firstName = contact.name?.firstName {
        return "\(firstName)"
    }
    else if let lastName = contact.name?.lastName {
        return "\(lastName)"
    }
    else {
        return "Unnamed contact"
    }
}

我不明白如何在此处显示这些名称:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("contacts", forIndexPath: indexPath) as! ContactsTableViewCell

    // Configure the cell...
    cell.contactsNumberLabel.text = contactsListNumbers[indexPath.row]
    cell.contactsNameLabel.text = contactListNames[indexPath.row]

    return cell
}

最佳答案

我不太确定这个库,但是我们可以看到 unwrappedContacts 是一个数组,其中包含 contactBook 中每个用户的所有信息。所以我们最好的选择是迭代这个数组,分解它然后将其分配给新数组。

根据我所做的一些研究,它说这个库包含一些字段,例如

Available fields: APContactFieldFirstName - contact first name APContactFieldMiddleName - contact middle name APContactFieldLastName - contact last name APContactFieldCompany - contact company (organization) APContactFieldPhones - contact phones array

struct ContactStructure
{
 var firstname:String?
 var lastname:String?
}

    var arrayOfContacts = [ContactStructure]()

      for each in unwrappedContacts
     {
        var firstname = each.APContactFieldFirstName as! String   
        var lastname  =  each.APContactFieldLastName as! String
        var SingleContact = ContactStructure()
        singleContact.firstname = firstname
        singleContact.lastname = lastname 
        arrayOfContacts.append(SingleContact)
        // Then reloadData of the tableView
     }

请注意,每个都是数组中的单个对象,因此当您执行 each. 时,您应该查看此类或结构所拥有的方法和属性

然后您将使用该 arrayOfContacts 来填充表格 View 的单元格

关于ios - 如何在 TableView 中显示 APAddressBook 的联系人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34042018/

相关文章:

ios - Swift 惰性和可选属性

Iphone ABUnknownPersonViewController 使用 allowsAddingToAddressBook = YES 问题

ios - 如何使用 NSTimer 在特定时间执行操作?

ios - 如何使用 Swift 将图像上传到 iOS 中的服务器?

ios - 通过 instagram API 删除 instagram 媒体上的评论

ios - 无法从联系人中获取 ABPerson 的图像

ios - 为什么 ABGroupAddMember 失败?它返回 NO 并且不设置 CFErrorRef 值

ios - 如何在 iPhone 中以编程方式设置锁屏、墙纸和铃声?

ios - 当弱引用对象(任意类型)被释放时,我可以 Hook 吗?

ios - DispatchQueue.main.asyncAfter 方法在特定调用中卡住 UI