Here is the code which I am using to get data and save data from plist.
i have hardcoded some data into plist beforehand.
i am able to read the data from plist, but not able to write it!!
(observation: and whenever i print the url, it is different every time, why is it like this?)
func savePropertyList(_ plist: [String:Any])
{
let path = Bundle.main.path(forResource: "PL", ofType: "plist")!
let url = URL(fileURLWithPath: path)
do{
let data = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
try data.write(to: url)
}
catch{
print(error.localizedDescription)
}
}
func loadPropertyList() -> [String:Any]?
{
let path = Bundle.main.path(forResource: "PL", ofType: "plist")!
let url = URL(fileURLWithPath: path)
do{
let data = try Data(contentsOf: url)
guard let dict = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String:Any] else{
return [:]
}
return dict
}
catch{
print(error.localizedDescription)
}
return [:]
}
On Apple platforms a bundle structure is read-only [1], so you won’t be able to modify this property list in place. If the property list is relatively small, the solution is straightforward: Write it to a location that is writeable, like your Documents directory. Get that location using code like this:
let u = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
observation: and whenever i print the url, it is different every time,
why is it like this?
I presume you’re testing this on iOS (or one of its child platforms, or the simulators thereof). In that case, your app’s install path will include a UUID because… well… Apple hasn’t ever said why, but that’s how it’s worked from day one.
ps This question is very specific to Apple platforms, and thus somewhat off-topic for Swift Forums, where the focus is on the Swift language itself. If you have further Apple-specific questions, try asking them over on Apple Developer Forums.
A bundle is a read-only structure. All Apple platforms except the Mac
enforce this requirement at runtime. On iOS, for example, any attempt
to modify your app’s bundle at runtime will fail with an error. The
Mac may or may not enforce this requirement at runtime, depending on
the context, but modifying your app’s bundle isn’t supported because
it breaks the seal on the app’s code signature.