Opening a New Document from File URL?

I have a sample document-based macOS app. I understand that you can open a new window or a new tab with some text.

import SwiftUI

struct ContentView: View {
	@Binding var document: TexDocument
	@Environment(\.newDocument) var newDocument
		
	var body: some View {
		VStack(spacing: 0) {
			topView
		}
	}
	
	private var topView: some View {
		Button {
			newDocument(TexDocument(text: "A whole new world!"))
		} label: {
			Text("Open new window")
				.frame(width: 200)
		}
	}
}

Suppose that I have a path to a text file whose security-scoped bookmark can be resolved with a click of a button. I wonder if you can open a new window or a new tab with the corresponding content?. I have done that in Cocoa. I hope I can do it in SwiftUI as well. Thanks.

Accepted Answer

Taking a look at openDocument, it says it can open document at a specific URL, provided that its bookmark is resolved. And it does open a file with security-scoped bookmark.

func loadBookmarks() async {
    for bookmarkItem in bookmarkViewModel.bookmarkItems {
    	// resolving a bookmark
        if let _ = resolveBookmark(bookmarkData: bookmarkItem.bookmarkData) {
            do {
                try await openDocument(at: bookmarkItem.bookmarkURL)
            } catch {
                print("\(error.localizedDescription)")
            }
        }
    }
}

struct BookmarkItem: Codable, Hashable {
    let bookmarkURL: URL
    let date: Date
    let bookmarkData: Data
    let open: Bool
}
Opening a New Document from File URL?
 
 
Q