How can I make plist content programatically?

This is my plist content in below, is there a way to make this content with code? instead just having it like as a string?

let test = """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
          <key>Label</key>
          <string>com.yourdomain.onstartup</string>
          <key>LimitLoadToSessionType</key>
          <string>Aqua</string>
          <key>Program</key>
          <string>/Applications/On Startup.app/Contents/MacOS/On Startup</string>
          <key>RunAtLoad</key>
          <true/>
</dict>
</plist>
"""

import Foundation

let plist: [String: Any] = [
    "Label": "com.yourdomain.onstartup",
    "LimitLoadToSessionType": "Aqua",
    "Program": "/Applications/On Startup.app/Contents/MacOS/On Startup",
    "RunAtLoad": true
]

let data = try! PropertyListSerialization.data(
    fromPropertyList: plist,
    format: .xml,
    options: 0
)
let string = String(decoding: data, as: UTF8.self)
print(string)

Output:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.yourdomain.onstartup</string>
    <key>LimitLoadToSessionType</key>
    <string>Aqua</string>
    <key>Program</key>
    <string>/Applications/On Startup.app/Contents/MacOS/On Startup</string>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

With Codable data, you can use a PropertyListEncoder, which works just like the JSONEncoder you may be more familiar with.

Leave a Comment