简体   繁体   English

将 iOS 联系人提取到 tableview,但直到我单击另一个选项卡栏项并返回 tableview 选项卡后,才会显示 Tableview 数据

[英]Fetched iOS contacts to tableview but the Tableview data is not showing until I click another tab bar item and come back to the tableview tab

This function is called in my "viewDidLoad()".这个函数在我的“viewDidLoad()”中被调用。 I am able to retrieve all contacts successfully, though the data doesn't show up, until I click another tab bar item, then return to the tableview tab bar item.我能够成功检索所有联系人,但数据没有显示,直到我单击另一个选项卡栏项,然后返回到 tableview 选项卡栏项。 Here is my code ..这是我的代码..

 func getContacts()
     {
         print("Attempting to fetch Contacts")
         let store = CNContactStore()

         store.requestAccess(for: .contacts) { (granted, err) in
             if let err = err {
                 print("failed to request Access", err)
                 return
             }
         if granted {
             print("access granted")
             let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]
             let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
            request.sortOrder = CNContactSortOrder.userDefault
             do {
                var contactNames = [ContactNames]()

                 try store.enumerateContacts(with: request, usingBlock: {(contact, stopPointerIfYouWantToStopEnumerating) in

                    contactNames.append(ContactNames(contact: contact))

                 })

                self.contactsArray = contactNames


             }catch let err {
                 print("Failed to enumerate contacts", err)
             }


         } else{
             print("access denied")
             }

         }

     }

Your data won't have been loaded by the first time the tableview is populated.您的数据不会在第一次填充 tableview 时加载。 It works when you navigate using the tabs because the data has loaded at the point you return to the tableview tab and this forces a reload of the tableview.当您使用选项卡导航时,它会起作用,因为数据已在您返回 tableview 选项卡时加载,这会强制重新加载 tableview。

Assuming your tableview data source is using self.contactsArray you just need to call tableview.reloadData() after assigning your data to self.contactsArray .假设您的 tableview 数据源使用self.contactsArray您只需要在将数据分配给self.contactsArray后调用tableview.reloadData()

Be sure to do this on the main thread.请务必在主线程上执行此操作。

self.contactArray = contactNames
DispatchQueue.main.async {
    self.tableView.reloadData()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM