Hi All, I'm very new to iOS development and Swift UI is my first coding language. I'm trying to link the users search results in Spotlight with the detail view that is stored in Core Data. I can search for users data in spotlight but when I tap on it, it's only appearing in the main view of the app. Is there anyways that I can use .onContinueUserActivity at the launch of the app or is there any different code that I have to use? I've searched for many articles but I couldn't get a solution. It would be good if anyone can share some links or guide here. Thank you.
.onContinueUserActivity(DetailView.productUserActivityType) { userActivity in
if let product = try? userActivity.typedPayload(Product.self) {
selectedProduct = product.id.uuidString
}
}
I get this code from Apple's State restoration app but I can't use this with Core Data.
Issue resolved with the following code. Might be helpful for future reference for anyone.
var coreDataProvider: PersistenceController = .shared
@State private var navigationSelection: Panel? = Panel.selectedView
@State private var searchedItem: CoreDataEntity = CoreDataEntity()
@State private var searchText: String = ""
@State private var isShowingDetailView: Bool = false
var body: some View {
ContentView(searchText: $searchText)
.onContinueUserActivity(CSSearchableItemActionType, perform: { activity in
// Navigate the search results to the respective view.
self.navigationSelection = .selectedView
guard let searchString = userActivity.userInfo?[CSSearchQueryString] as? String else {
return
}
// Spotlight search string
self.searchText = searchString
})
.onContinueUserActivity(CSSearchableItemActionType, perform: { activity in
self.navigationSelection = .selectedView
if let info = activity.userInfo,
let objectIdentifier = info[CSSearchableItemActivityIdentifier] as? String,
let objectURI = URL(string: objectIdentifier) {
let uri = objectURI
let container = coreDataProvider.persistentContainer
if let objectID = container.persistentStoreCoordinator.managedObjectID(forURIRepresentation: uri) {
if let item = container.viewContext.object(with: objectID) as? CoreDataEntity {
// Switch to the state corresponding to the item
self.searchedItem = item
self.isShowingDetailView = true
}
}
}
})
.sheet(isPresented: $isShowingDetailView) {
self.isShowingDetailView = false
} content: {
SpotlightResultsView(searchedItem: $searchedItem, isShowingDetailView: $isShowingDetailView)
}
}
Hope this is helpful and have fun!