Search code examples
swiftmacosnsarraynsdictionarynskeyedarchiver

NSKeyedArchiver.archiveRootObject fails to save


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.


Solution

  • 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"))