Post

Replies

Boosts

Views

Activity

Reply to How can I share SwiftData @Model between widget and app?
Containers are references. The correct way to achieve this I think would be by using AppDependencyManager. Here is a working example: @Model final class Test: @unchecked Sendable { var text: String init(text: String) { self.text = text } } struct InsertTestIntent: AppIntent { static var title: LocalizedStringResource = "Insert model" static var openAppWhenRun: Bool = true static var isDiscoverable: Bool = false @Parameter(title: "Text") var text: String @Dependency private var modelContainer: ModelContainer init(text: String) { self.text = text } init() {} @MainActor func perform() async throws -> some IntentResult { modelContainer.mainContext.insert(Test(text: text)) return .result() } } struct ContentView: View { @Query private var items: [Test] @State private var text = "" var body: some View { NavigationStack { List { TextField("Text", text: $text) Button("Insert model", intent: InsertTestIntent(text: text)) Section { ForEach(items) { item in Text(item.text) } } } .navigationTitle("Home") } } }
Feb ’24
Reply to Drag and drop to open window in SwiftUI app
It is a little trickier to do in SwiftUI but possible, though I have only tested this on visionOS. You can find the code below. You will also need to update your Info.plist and add NSUserActivityTypes array with your activities you want to open a new window. import SwiftUI struct Activity { static let openWindow = "com.ericlewis.openWindow" } struct ContentView: View { @State private var text = "root" var body: some View { Button(text) { // noop, makes it easier to grab and drag. } .onDrag { let payload = "destination payload \(Int.random(in: Int.min...Int.max))" let userActivity = NSUserActivity(activityType: Activity.openWindow) try! userActivity.setTypedPayload(["text": payload]) let itemProvider = NSItemProvider(object: payload as NSString) itemProvider.registerObject(userActivity, visibility: .all) return itemProvider } .onContinueUserActivity(Activity.openWindow) { userActivity in if let dict = try? userActivity.typedPayload([String: String].self) { self.text = dict["text"]! } } } }
Feb ’24