创建 plist 并将其复制到文件夹 MacOS Swift
create plist and copy it to folder MacOS Swift
我一直在绞尽脑汁想如何在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")
}
首先NSSearchPathForDirectoriesInDomains
已经过时了,强烈推荐使用URL相关的API。
此代码创建一个 URL 指向 /Library/LaunchDaemons
let libraryDirectory = try! FileManager.default.url(for: .libraryDirectory, in: .localDomainMask, appropriateFor: nil, create: false)
let launchDaemonsFolder = libraryDirectory.appendingPathComponent("LaunchDaemons")
我一直在绞尽脑汁想如何在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")
}
首先NSSearchPathForDirectoriesInDomains
已经过时了,强烈推荐使用URL相关的API。
此代码创建一个 URL 指向 /Library/LaunchDaemons
let libraryDirectory = try! FileManager.default.url(for: .libraryDirectory, in: .localDomainMask, appropriateFor: nil, create: false)
let launchDaemonsFolder = libraryDirectory.appendingPathComponent("LaunchDaemons")