Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary loading binary plist on linux (swift)

Tags:

linux

macos

swift

As the implementation of serverside swift is different, there is a fundamental (to my project) part of the NSArray and NSDictionary missing. Namely the dictionaryWithContentsOfFile: method loads only non-binary plist files on Linux so my app works only on macOS. There some older questions on StackOverflow answers re this topic, but they lead to sites that don't exist anymore. So my question is: Is there any easy way to load binary plist into NSDictionary without having to use some "decompile" outside script and if there is no solution, what would be the most elegant solution using one?

like image 851
Ondrej Rafaj Avatar asked Mar 01 '26 23:03

Ondrej Rafaj


1 Answers

From my understanding native handling of .plists in Swift is via PropertyListSerialization:

// PropertyListSerialization Method

var plistFormat = PropertyListSerialization.PropertyListFormat.binary
let plistPath: String? = Bundle.main.path(forResource: "binary", ofType: "plist")!
let plistBinary = FileManager.default.contents(atPath: plistPath!)!

guard let propertyList = try? PropertyListSerialization.propertyList(from: plistBinary, options: [], format: &plistFormat) else {
    fatalError("failed to deserialize")
}
print(propertyList as! [String:Any])

Result:

"["MyDictionary": {\n MyArray = (\n Two,\n One\n);\n}]\n"

The NSDictionary way, as you know would likely be:

// NSDictionary Method

if let url = Bundle.main.url(forResource:"binary", withExtension: "plist"),
    let myDict = NSDictionary(contentsOf: url) as? [String:Any] {
    print(myDict)
}

Result:

"["MyDictionary": {\n MyArray = (\n Two,\n One\n);\n}]\n"

Comparing the end result of both methods is identical using a binary .plist; I would imagine it should work (?), or at least give you some idea to an alternate means of reading/writing the data.

like image 181
l'L'l Avatar answered Mar 04 '26 14:03

l'L'l



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!