Please forgive me for my lack of knowledge, I'm trying to make my first iOS App, and my goal is to import all of my contacts into a swiftui view:
//ContentView.swift
import SwiftUI
struct ContentView: View {
var contact = contactData
@ObservedObject var contacts = ContactList()
var body: some View {
NavigationView {
List {
ForEach(contact) { item in
VStack(alignment: .leading) {
HStack {
Text(item.contactName)
}
}
}
.onDelete { index in
self.contacts.contact.remove(at: index.first!)
}
}
.navigationBarTitle(Text("Contacts"))
.navigationBarItems(
trailing: EditButton()
)
}
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
struct Contacts: Identifiable {
var id = UUID()
var contactName: String
}
let contactData = [
Contacts(contactName: "Foo Bar"),
Contacts(contactName: "Johnny Appleseed")
]
and
//ContactList.swift
import Combine
class ContactList: ObservableObject {
@Published var contact: [Contacts] = contactData
}
Using the Combine API and the .onDelete
function, I would like to delete multiple contacts (currently not a feature in iOS), then return them back into the contacts app.
I'm stuck though at pulling in the contact list, and I've tried multiple different ways of doing this with Swift like: Fetching all contacts in iOS Swift?
var contacts = [CNContact]()
let keys = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)]
let request = CNContactFetchRequest(keysToFetch: keys)
do {
try self.contactStore.enumerateContactsWithFetchRequest(request) {
(contact, stop) in
// Array containing all unified contacts from everywhere
contacts.append(contact)
}
}
catch {
print("unable to fetch contacts")
}
But that hasn't seemed to work properly without throwing a bunch of errors. I'm not so worried about deletion at the moment, but more primarily focused on just importing the contacts.
Does anyone know if there's a good way to do this using SwiftUI and the Contacts API? or can at least point me in the right direction? I understand I am on a Xcode 11 Beta 5, which may cause problems with deprecation of different API's, but it seems that the Contact API has been relatively unchanged in Xcode 11.