When I write code with UIKIt or Cocoa, I usually create and use FileManager.default in AppDelegate or a base view controller. In Cocoa, for example, I would write something like the following.
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let defaultFileManager = FileManager.default
func applicationDidFinishLaunching(_ aNotification: Notification) {
}
func applicationWillTerminate(_ aNotification: Notification) {
NSApp.terminate(nil)
}
}
import Cocoa
class HomeViewController: NSViewController {
let appDelegate = (NSApp.delegate as! AppDelegate)
override func viewDidLoad() {
super.viewDidLoad()
if appDelegate.defaultFileManager.fileExists(atPath: some file path) {
}
}
}
So my question is where I can create FileManager.default so that I use it under different Views in SwiftUI? Muchos thankos.
I've figured it out. You use UIApplicationDelegateAdaptor for iOS, NSApplicationDelegateAdaptor for Cocoa.
import SwiftUI
@main
struct MyCrazyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class AppDelegate: UIResponder, UIApplicationDelegate {
let fileManager = FileManager.default
}
In this fashion, you will access to fileManager in AppDelegate inside another View.