简体   繁体   中英

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()". 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. 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. 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.

Assuming your tableview data source is using self.contactsArray you just need to call tableview.reloadData() after assigning your data to self.contactsArray .

Be sure to do this on the main thread.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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