Skip to content

Instantly share code, notes, and snippets.

@sturdysturge
Last active July 20, 2020 18:28
Show Gist options
  • Save sturdysturge/6901041cf6905ae3f5958516d745cfb3 to your computer and use it in GitHub Desktop.
Save sturdysturge/6901041cf6905ae3f5958516d745cfb3 to your computer and use it in GitHub Desktop.
RevDoc UserActivityView
import SwiftUI
import CoreSpotlight
import MobileCoreServices
struct UserActivityView: View {
@State var data: [String]
@State var openedID = String()
@State var alertPresented = false
init() {
if let stringArray = UserDefaults.standard.stringArray(forKey: "data") {
self._data = State<[String]>(initialValue: stringArray)
}
else {
var data = [String]()
for _ in 1...10 {
data.append(UUID().uuidString)
}
self._data = State<[String]>(initialValue: data)
UserDefaults.standard.set(data, forKey: "data")
}
}
func indexItem(atIndex index: Int) {
let uuid = data[index]
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
attributeSet.title = "A search item for my app"
attributeSet.contentDescription = uuid
let item = CSSearchableItem(uniqueIdentifier: uuid, domainIdentifier: "com.MyCompany", attributeSet: attributeSet)
CSSearchableIndex.default().indexSearchableItems([item]) { error in
if let error = error {
assertionFailure("Failed to index with error\n\(error)")
} else {
print("Saved successfully")
}
}
}
func presentAlert(_ userActivity: NSUserActivity) {
if let id = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
openedID = id
alertPresented = true
}
}
var body: some View {
List(0..<data.count, id: \.self) { index in
Button("\(data[index])") {
indexItem(atIndex: index)
}
}
.userActivity("com.MyCompany.MyApp.searchActivity", element: openedID) {
string, activity in
if !string.isEmpty {print("Updated \(string) \(activity.activityType)")}
}
.onContinueUserActivity("com.MyCompany.MyApp.searchActivity") { activity in
print("Continue after Handoff")
}
.alert(isPresented: $alertPresented) {
Alert(title: Text("onContinueUserActivity"), message: Text(openedID), dismissButton: .default(Text("Okay")))
}
.onContinueUserActivity(CSSearchableItemActionType, perform: presentAlert)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment