我一直在思考如何在MacOS中创建plist并将其写入特定的文件夹目录。就我而言,是/ Library中的LaunchDaemons文件夹。我知道如何创建plist,但是知道如何写给我遇到问题的LaunchDaemons文件夹。根据我的理解,以下这段代码是针对沙箱的,但是如何在沙箱之外进行呢?欢呼声
let fileManager = FileManager.default
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let path = documentDirectory.appending("test.plist")
我已经在收到的帮助下添加了代码,没有任何错误,但是没有向文件夹中写入任何内容。这是代码:
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")
}
答案 0 :(得分:1)
首先NSSearchPathForDirectoriesInDomains
已过时,强烈建议始终使用与网址相关的API。
此代码创建指向/Library/LaunchDaemons
的URL
let libraryDirectory = try! FileManager.default.url(for: .libraryDirectory, in: .localDomainMask, appropriateFor: nil, create: false)
let launchDaemonsFolder = libraryDirectory.appendingPathComponent("LaunchDaemons")