Search code examples
swiftmacosplistnsfilemanager

create plist and copy it to folder MacOS Swift


I have been racking my brain on how to create and write a plist to a certain Folder Directory in MacOS. In my case to the LaunchDaemons folder in /Library. I know how to create the plist but its the writing to the LaunchDaemons folder that I am having issues with. This code below from my understanding is for the sandbox but how do I do it outside of the sandbox? Cheers

 let fileManager = FileManager.default
 let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
 let path = documentDirectory.appending("test.plist")

I have added the code with the help I have received and have no errors but it is not writing anything to the folder. Here is the code:

 let libraryDirectory = try! FileManager.default.url(for: .libraryDirectory, in: .localDomainMask, appropriateFor: nil, create: false)
    let launchDaemonsFolder = libraryDirectory.appendingPathComponent("LaunchDaemons/test.plist")

    if FileManager.default.fileExists(atPath: launchDaemonsFolder.path) {

        print(launchDaemonsFolder)


        let plistDictionary : [String: Any] = [
            "ExitTimeOut": 600,
            "Label": "BOOT.SHUTDOWN.SERVICE",
            "ProgramArguments": ["/test.sh"] as Array,
            "RunAtLoad": false,
            "WorkingDirectory": "/"

        ]

        let dictionaryResult = NSDictionary(dictionary: plistDictionary)
        let fileWritten = dictionaryResult.write(to: launchDaemonsFolder, atomically: true)
        print("is the file created: \(fileWritten)")



    } else {

        print("File Exists")

    }

Solution

  • First of all NSSearchPathForDirectoriesInDomains is outdated, it's highly recommended to use the URL related API anyway.

    This code creates an URL pointing to /Library/LaunchDaemons

    let libraryDirectory = try! FileManager.default.url(for: .libraryDirectory, in: .localDomainMask, appropriateFor: nil, create: false)
    let launchDaemonsFolder = libraryDirectory.appendingPathComponent("LaunchDaemons")