timfi timfi - 2 months ago 51
Swift Question

DKImagePickerController: how to save DKAsset array to NSUserDefaults

I've implemented the cocoapod DKImagePickerController in my app and I want to use the built-in function to remember the selection on app restart:

pickerController.selectedAssets = selAssets[sender]


However, I can't seem to work out how to save the [[DKasset]] (array of array of DKasset).

I've tried:

func getUserSettings()
{
selAssets = NSKeyedUnarchiver.unarchiveObjectWithFile(fileInDocumentsDirectory("assets")) as! [[DKAsset]]
}

func setUserSettings()
{
NSKeyedArchiver.archiveRootObject(selAssets, toFile: self.fileInDocumentsDirectory("assets"))
}


But the getUserSettings() doesn't fill the array with usable objects. I've also tried to user NSUserDefaults' objectForKey, but that doesn't seem to be compatible with DKAsset. The class DKAsset is a subclass of NSObject.

How can I save and load this array?

The cocoa pod:
https://cocoapods.org/pods/DKImagePickerController

Answer

for anyone who wants to do this:

func loadFromNSDefaults()
{
    if UserDefaults.standard.stringArray(forKey: "selection") != nil
    {
        assetIdentifier = UserDefaults.standard.stringArray(forKey: "selection")!
    }
    fetchAsset.removeAll()
    selAssets.removeAll()
    let options = PHFetchOptions()
    for i in 0..<assetIdentifier.count
    {
        print(i)
        fetchAsset.append(PHAsset.fetchAssets(withLocalIdentifiers: assetIdentifier, options: options).object(at: i))
        selAssets.append(DKAsset.init(originalAsset: fetchAsset[i]))
    }
}

func saveToNSDefaults(assets: [DKAsset])
{
    assetIdentifier.removeAll()
    for i in 0..<assets.count
    {
        assetIdentifier.append((assets[i].originalAsset?.localIdentifier)!)
        print(assets[i].originalAsset?.localIdentifier)
    }
    UserDefaults.standard.setValue(assetIdentifier, forKey: "selection")
}
Comments