CKAsset Upload error with Long Lived Operations

Viewed 53

I am receiving an error when the app is trying to upload a CKAsset in a long lived operation once the user has connected back to internet. On re-opening the app the long lived operation returns this error.

related decl 'e' for CKErrorCode(_nsError: <CKError 0x28352bf60: "Invalid Arguments" (12); "Long Lived Operation <CKModifyRecordsOperationInfo: 0x104f2c950> may not save a record with asset <CKAsset: 0x104ff6760; uploadRank=0, path=~/Containers/Data/Application/UUID/Documents/rawContent, UUID= >, whose fileURL file:///var/mobile/Containers/Data/Application/UUID/Documents/rawContent is inaccessible">)

The path is accessible by me and is public. What is causing this error?

1 Answers

You may get this error when the url of the file that you want to upload is no longer accessible for the CKOperation when you replay / restart it. You can solve this by storing the url as a bookmark when starting the initial operation, like this:

 if let data = try? url.bookmarkData(options: .minimalBookmark, includingResourceValuesForKeys: nil, relativeTo: nil) {
     UserDefaults.standard.set(data, forKey: "url")
 }

Before you setup and restart the long lived operation, restore the bookmark like this:

var isStale = false
guard let data = UserDefaults.standard.data(forKey: "url"),
      let url = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &isStale),
      url.startAccessingSecurityScopedResource() else {
    return
}

Include this in the final completion handler of the restarted operation:

url.stopAccessingSecurityScopedResource()
Related