Purge On-Demand Resources programmatically

I have a Swift app that includes On-Demand Resources, I haven't found any official solution to purge/remove ODR programmatically.

But I found a workaround to purge the ODR pragmatically by

let request = NSBundleResourceRequest(tags: [resource.tag])
let dispatchGroup = DispatchGroup()

dispatchGroup.enter()
request.conditionallyBeginAccessingResources { [weak self] resourcesAvailable in
    defer { dispatchGroup.leave() }
    guard resourcesAvailable else { return }

    do {
        try self?.fileArchiveProvider.removeFile(at: resource.absoluteOriginURL.deleteLastPathComponents(components: 2))
    } catch {
        print("   \(error)")
    }
}
dispatchGroup.wait()
request.endAccessingResources()


The code above works well with the simulator, but it doesn't work with real device. On real device, it throws exception:

   Error Domain=NSCocoaErrorDomain Code=513 "“com.flashgordon.asset-pack-5d28ed3b881fb0e1f33c7f139b8ea675.assetpack” couldn’t be removed because you don’t have permission to access it." UserInfo={NSUserStringVariant=(
    Remove
), NSFilePath=/var/mobile/Library/OnDemandResources/AssetPacks/48EE9540-1F9E-415F-BBC9-6EC07DBD1782/7452398430216108346/com.unibet.flashgordon.asset-pack-5d28ed3b881fb0e1f33c7f139b8ea675.assetpack, NSUnderlyingError=0x2800e4270 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}


There are also many people asking similar questions:

https://stackoverflow.com/questions/48070294/on-demand-resources-force-purge-clear-of-downloaded-resource-bundles

https://stackoverflow.com/questions/37599767/on-demand-resources-purging


So my question is: Is there any way to force purge ODR from bundle programmatically? Thanks.

Replies

There is currently no way to programmatically purge ODR resources. It is up to discretion the OS.


When a new network request for ODR content is initiated, the system will do a sort of inventory check, checking what is currently in memory and if there’s room for new memory. This check also takes into account several other metrics, such as which assets are currently being used, which were used recently, is the asset being used for the UI, etc.


After this is done, the system will determine how much of the chosen assets are to be purged, so that there is enough room to fit the new content. If I remember correctly, the OS will try and delete whole assetpacks. What this means is, if the system is purging assets, it will purge resources that are grouped together such as, all assets from Level 1, Level 2, and Level 3, provided the user is on Level 4. So, the system might purge slighly more space than exactly needed.


If you would like to change your app's ODR assets, you will have to submit an update to your app.


Hope that helps!