Reputation: 3221
I have a group of custom objects that I'm converting to NSMutableDictionary
's, and then creating an array out of them (this part is currently working as expected).
I'm then attempting to save that array of data as a file using NSKeyedArchiver
. However, the result of NSKeyedArchiver.archiveRootObject
always returns false
.
Below is my logic for saving - am I missing something obvious, or perhaps is this the wrong approach? Thank you!
var groupsArray = [Any?]()
for group in file!.groups{
for obj in group.children {
let objDict = obj.convertToDictionary()
groupsArray.append(objDict)
}
}
let documents: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let filePath: String = URL(fileURLWithPath: documents).appendingPathComponent("file.archive").absoluteString
let save: Bool = NSKeyedArchiver.archiveRootObject(groupsArray, toFile: filePath)
EDIT: This also fails if trying to save to the .desktop
or the .caches
directories.
Upvotes: 0
Views: 1979
Reputation: 4355
The issue here is .absoultestring
. If the URL object contains a file URL, then we should use .path
for working with FileManager
or PathUtilities
etc. So here replacing .absoultestring
with .path
will solve the issue
for more details about their difference please refer this answer
Upvotes: 1
Reputation: 756
try this method to save
1.Method returns filepath.
func filePath(key:String) -> String {
let manager = FileManager.default
let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
return (url!.appendingPathComponent(key).path)
}
2.Code to save to a file using NSKeyedArchiver.
NSKeyedArchiver.archiveRootObject(groupsArray, toFile: filePath(key: "file.archive"))
Upvotes: 0