Where and How to Create FileManager as a Singleton?

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.

Answered by Tomato in 705469022

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.

Assuming you are using MVVM with SwiftUI, your ViewModel can still refer to FileManager.default.

Or SwiftUI itself can refer to FileManager.default... or you can assign it to a local var in a SwiftUIView, like...

@State private var manager = FileManager.default

FileManager.default is the same thing, wherever you refer to it... (that's the point of a Singleton), so you don't need to pass it in to your View.

You are not really creating the Singleton, you are just referring to it.

Is that what you are asking?

Accepted Answer

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.

Where and How to Create FileManager as a Singleton?
 
 
Q