Unintelligible Error of CloudKit Failing to delete Asset File - swift

So, I'm building a simple diary app in which the diary pages are saved in Core Data and synced with CloudKit. I have a lot of database operations, which I do asynchronously in the background. For example, when the user writes an entry, I save the diary page every 5 seconds or when the user adds an image to it.
I do not touch anything with CloudKit rather than using an NSPersistentCloudKitContainerand these lines:
cloudKitContainer.automaticallyMergesChangesFromParent = true
guard let containerId = cloudKitContainer.containerIdentifier,
let description = container.persistentStoreDescriptions.first else {
print(#function, "Could not initalizeCloudKitScheme.")
return
}
let options = NSPersistentCloudKitContainerOptions(containerIdentifier: containerId)
description.cloudKitContainerOptions = options
When saving and deleting diary pages I get the following error. The error occurs especially when adding and deleting images, I guess due to their size:
PFCloudKitExporter exportOperationFinished:withSavedRecords:deletedRecordIDs:operationError:]_block_invoke(492): Failed to delete asset file: file:///var/mobile/Containers/Data/Application/D62B434E-A968-423B-8408-9461A97DA8D1/Library/Application%20Support/ckAssetFiles/3F783A57-2038-45E8-8D93-1DD0A7EBD89F.fxd
Error Domain=NSCocoaErrorDomain Code=4 "“3F783A57-2038-45E8-8D93-1DD0A7EBD89F.fxd” couldn’t be removed." UserInfo={NSUserStringVariant=(
Remove
), NSFilePath=/var/mobile/Containers/Data/Application/D62B434E-A968-423B-8408-9461A97DA8D1/Library/Application Support/ckAssetFiles/3F783A57-2038-45E8-8D93-1DD0A7EBD89F.fxd, NSUnderlyingError=0x281995e90 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
Can anyone explain how this error can occur, if I am only doing basic operations on my dataset?

Related

How do I use a CoreData model from a framework within an app group?

I'm packaging a basic framework that's got some repositories around CoreData models, that package contains the .xcdatamodeld file. If I use it in my app extensions, for example, it's not in the app groups folder.
If I add the code below in my PersistentContainer subclass, I'm receiving the error below:
let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.{bundleID}")?.appendingPathComponent("{Name}.sqlite", isDirectory: false)
let storeDescription = NSPersistentStoreDescription(url: url!)
persistentStoreDescriptions = [storeDescription]
This is the error message:
<NSPersistentStoreCoordinator: 0x600002ce9ab0>: Attempting recovery from error encountered during addPersistentStore: Error Domain=NSCocoaErrorDomain Code=512 "The file couldn’t be saved." UserInfo={reason=Failed to create file; code = 2}
How can I have a framework with a CoreData model, which is placed in the App Group for all targets to use?

Move selected file

I have a Swift macOS application, and I'm trying to allow the user to open a file using NSOpenPanel and then rename that file to another name.
I have enabled sandboxing with User Selected File set to Read/Write.
Here is my code:
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
if panel.runModal() == .OK {
let url = panel.url!
do {
try FileManager.default.moveItem(at: url, to: url.deletingLastPathComponent().appendingPathComponent("New name.test"))
}
catch let x {
print(x)
}
}
It simply asks the user to choose a file, and then renames the file to "New name.test". However, I get an error message saying
Error Domain=NSCocoaErrorDomain Code=513 "“Untitled” couldn’t be moved because you don’t have permission to access “untitled folder 30”." UserInfo={NSSourceFilePathErrorKey=/Users/user/Desktop/untitled folder 30/Untitled.txt, NSUserStringVariant=(
Move
), NSDestinationFilePath=/Users/user/Desktop/untitled folder 30/New name.test, NSFilePath=/Users/user/Desktop/untitled folder 30/Untitled.txt, NSUnderlyingError=0x6000032115c0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
I'm pretty sure this is because even though I have access to that specific file, I do not have access to its parent directory which is what I need in order to rename the file.
This question is very similar to Application Sandbox: renaming a file doesn't work, however none of the answers work for me.
The most promising answer is here, and I tried adding the document types & using NSFileCoordinator, but it still didn't work, with this error:
an error was received from pboxd instead of a token. Domain: NSPOSIXErrorDomain, code: 1
Is this even possible, or am I missing something obvious?

Can't access .csv data using MLDataTable

I am trying to read the content of a .csv file using the framework CreateML to read csv data.
Fhe following code generates an error even though the file exists:
let csvURL = URL(fileURLWithPath: "/Volumes/MAC HDD/Data/Data.csv")
let fm = FileManager()
if (fm.fileExists(atPath: csvURL.path)) {
let dataTable = try! MLDataTable(contentsOf: csvURL)
// accessing first column
let col_1 = Array.init(dataTable["col1"])
}
I get the following error message:
Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: CreateML.MLCreateError.generic(reason: "No files corresponding to the specified path (file:///Volumes/MAC%20HDD/Data/Data.csv)")
I have checked nearly everything but can't get any results. What am I doing wrong?
I found out by my self what the problem is.
I have implemented this code in a Xcode project to read csv data, but the CreateML framework is just working for Xcode Playground and not within a Xcode Project! It was mentioned at the end of the WWDC 2018 session video 703.
The code example above is working fine with Xcode Playground.
It would have saved me a lot of time if there had been a warning when importing the framework.

Swift 4 | Referencing database file for SQLite queries "unable to open database file"

To begin, here is an image of my current project file set-up
I am using the following in this project:
import UIKit
import SQLite
import GRDB
When I execute the following code :
{
tagString = x
let dbQueue = try! DatabaseQueue(path: "data.db" )
try! dbQueue.inDatabase { db in
let rows = try Row.fetchCursor(db, "SELECT * FROM quotes WHERE genre = ? AND LENGTH(quote) < 100",
arguments: [tagString])
I get the following error "unable to open database file" as well as the warning "could not execute support code to read Objective-C class data in the process. This may reduce the quality of type information available."
I have tried changing "data.db" to simlpy "data", but that does not work.
The only solution I have found is when I write the complete path from my computer AND run it on a simulated app. If I try to use the entire path (ex. /Users/myName/Desktop/AppName/data.db) on my phone, the program crashes ( I assume because that memory location does not exist on the phone)
Question: Is my calling of the database correct? If so, any ideas of why It might not be able to find it?
Thankyou.
You get the "unable to open database file" error because you don't specify a valid path to your database.
On iOS, application files must be created at a valid path. Valid paths include paths inside the application's Documents folder. For example:
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let dbPath = documentsPath.appendingPathComponent("data.db")
let dbQueue = try DatabaseQueue(path: dbPath)
Please refer to the File System Basics chapter of iOS documentation for more information.

WKRefreshBackgroundTask cleanupStorage Error attempting to reach file

Whats this error I get when making a URLBGTask in WatchOS4 on the Simulator?
2017-09-28 16:05:26.452999+0900 MiFollowers WatchKit Extension[4628:4012814] [bg_app_refresh] -[WKRefreshBackgroundTask cleanupStorage]_block_invoke:213: Error attempting to reach file:///Users/ryuuzaki/Library/Developer/CoreSimulator/Devices/2E4D6389-93B7-4542-B07F-9A02C720B9AF/data/Containers/Data/PluginKitPlugin/FA4415DF-D984-4394-80B9-EDA199AB587E/Library/com.apple.watchkit/bktaskapp_(null): Error Domain=NSCocoaErrorDomain Code=260 "The file “bktaskapp_(null)” couldn’t be opened because there is no such file." UserInfo={NSURL=file:///Users/ryuuzaki/Library/Developer/CoreSimulator/Devices/2E4D6389-93B7-4542-B07F-9A02C720B9AF/data/Containers/Data/PluginKitPlugin/FA4415DF-D984-4394-80B9-EDA199AB587E/Library/com.apple.watchkit/bktaskapp_(null), NSFilePath=/Users/ryuuzaki/Library/Developer/CoreSimulator/Devices/2E4D6389-93B7-4542-B07F-9A02C720B9AF/data/Containers/Data/PluginKitPlugin/FA4415DF-D984-4394-80B9-EDA199AB587E/Library/com.apple.watchkit/bktaskapp_(null), NSUnderlyingError=0x79b0e340 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
Any of you bright minds out there know what all this means?
I was getting this too. Drove me nuts for the last two days.
I'm still not sure if it is a bug or "feature" to require you to use the userInfo property. This is happening if you don't get the userInfo property from the background refresh task in the handle(_ backgroundTasks) method. Any access of the property works. A simple workaround one to get rid of the error is to schedule your next background refresh in the handle method with backgroundTask.userInfo in the userInfo: parameter which just keeps assigning nil to the next task.
WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: refreshDate, userInfo: backgroundTask.userInfo) { (error) in
if let error = error {
print ("Background task error:\(error.localizedDescription)")
}
}
Of course this workaround means you won't be able to use userInfo. Better code might be to stick something in there such as the scheduling date or an identifier for the task, or a dictionary of [String:Any] for both.