Getting a SwiftUI document’s name is not intuitive so I’m writing this article to share what I learned.
Start by adding an environment variable for the document configuration. The DocumentConfiguration struct holds the document’s file URL.
@Environment(\.documentConfiguration) private var configuration: DocumentConfiguration?
Use the document configuration’s fileURL property to get the document’s file URL. Use the URL’s lastPathComponent property to get the document’s file name.
The file name includes the file extension. If you don’t want the file extension, call the URL’s deletingPathExtension function to remove the file extension.
Example code:
if let url = configuration?.fileURL {
let name = url.deletingPathExtension().lastPathComponent
}