timfi timfi - 1 year ago 179
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:

Answer Source

for anyone who wants to do this:

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

func saveToNSDefaults(assets: [DKAsset])
    for i in 0..<assets.count
    UserDefaults.standard.setValue(assetIdentifier, forKey: "selection")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download