Reputation: 311
I need to persist 5 boolean values to keep track of user's progress in the app. I thought using Core Date for this purpose was overkill so I decided to use Property List (PList) instead.
In my app, there is ToolTipData.plist
where I store 5 boolean values. The default boolean values are false. And I want to change the values to true in certain occasions.
Here is how I update the value in dictionary and write to plist:
static func updatePList() {
if let path = Bundle.main.path(forResource: "TooltipViewData", ofType: "plist") {
let dic = NSMutableDictionary(contentsOfFile: path)
dic?.setValue(NSNumber.init(booleanLiteral: true), forKey: "firstToolTipViewSeen")
if dic?.write(toFile: path, atomically: true) == true {
print("saved")
} else {
print("not saved")
}
print("reading updated plist: \(NSMutableDictionary(contentsOfFile: path))")
}
}
As a result, I get saved
prints and
reading updated plist: Optional({
firstToolTipViewSeen = 1;
secondToolTipViewSeen = 0;
thirdToolTipViewSeen = 0;
})
Then, I click the Plist file in the app then I find that
firstToolTipViewSeen
's value is still NO
even though I updated to YES
through above method. Is PList file not supposed to be updated or am i doing something wrong?
Thanks
Upvotes: 0
Views: 609
Reputation: 5223
Files in the app's bundle cannot be written.
You should create the plist in the Library
directory and then modify from there.
Here's how to create the file:
var appDir = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)
let plistURL = documentDirectoryURL.URLByAppendingPathComponent("TooltipViewData.plist")
do {
let fileExists = try plistURL.checkResourceIsReachable()
if !fileExists {
// create the plist, or move the plist from the main app bundle to plistURL
}
} catch let error as NSError {
print(error)
}
You can then save to the plist like you did before, this time using the URL plistURL
.
Just a suggestion: Save user's prefences to NSUserDefaults
Upvotes: 1