UIManagedDocument not opening - ios

If you create a new document and a file with same name does not exist in the current directory, then the app freezes. In particular the open function for the UIManagedDocument class does not call its completion handler.
On the other hand if the file does already exist in the current directory, then the open function does call the completion handler. In this case, however, there is a Core Data error printed to console.
I am testing on the iOS 12 Simulator with Xcode 10. Also tested on device.
CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/ruben/Library/Developer/CoreSimulator/Devices/####/data/Containers/Data/Application/####/tmp/mydoc.doccy/StoreContent/persistentStore options:{
NSPersistentStoreRemoveStoreOnCleanupKey = 1;
} ... returned error Error Domain=NSCocoaErrorDomain Code=134080 "(null)" UserInfo={NSUnderlyingException=Can't add the same store twice} with userInfo dictionary {
NSUnderlyingException = "Can't add the same store twice";
}
Example project

Turns out after creating the document and saving to a temporary location, you need to call close first, before importing and opening it.

Related

iOS 14 NSItemProvider loadDataRepresentation() returns nil data for specified types

Setup:
I am using PHPickerViewController to allow the user to select photos. I've implemented the PHPickerViewControllerDelegate protocol method picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]). I am getting the itemProvider from the results array.
Problem:
I need to access the data for the selected image. There is a method on NSItemProvider called loadDataRepresentation(), which takes a type identifier string and should return the image data in its completion block.
When I call this method sometimes it returns data, sometimes it doesn't. I've tried this for the multiple registered type identifiers for each provider, and I'm seeing the same thing. Sometimes it will return JPEG data, but not HEIF, other times only HEIF, and sometimes it won't return any data at all. This is consistent in that the same photo exhibits the same result each time I try to load its data.
When there is no data I see the following error:
Upload preparation for claim D8C281B7-CCCE-4299-95BF-9355FCF340E4 completed with error: Error Domain=NSCocoaErrorDomain Code=260 "The file “7AB1AB3F-7643-45C1-9DD9-5F5642965C3A.jpeg” couldn’t be opened because there is no such file."
Is there something I need to do to the photo before attempting to load its data? Maybe I'm missing a step here? This happens for photos I took directly with my iPhone XR. I am not using iCloud Photos, all photos are on the device.
"public.image" this identifier seems to be able to get all type of photos.
example : -
loadDataRepresentation(forTypeIdentifier: "public.image")
If you're getting this error in simulator it seems like it may be an OS bug, because doing a Device > Erase All Content and Settings.. to reset the simulator fixed this for me.

UIDocumentPickerController access denied Cocoa Error 257

I'm trying to import a custom file from one of my apps to another one (let's call them App_A and App_B). If I export the file directly from App_A and in the share sheet I select App_B everything works fine.
My problem is that the file is saved in iCloud Drive so the user can access it through the system's File app. When I try to select the same file from Files app or in App_B through UIDocumentPickerViewController.
In both cases I run the following code (inside UIDocumentPickerDelegate or AppDelegate):
let access = url.startAccessingSecurityScopedResource()
var error: NSError? = nil
NSFileCoordinator().coordinate(readingItemAt: url, error: &error) { (coorURL) in
do{
let data = try Data(contentsOf: coorURL)
}catch{
print("manage error: \(error.localizedDescription)")
}
if access{
url.stopAccessingSecurityScopedResource()
}
}
The error I get is always the same:
Error Domain=NSCocoaErrorDomain Code=257 ... NSUnderlyingError=0x2803e07b0 {Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied"}} and url.startAccessingSecurityScopedResource() returns always false.
I'm doing this on Xcode 11.4.1, Swift 5, iOS 13.3.1 on device and 13.4.1 on simulator, but the result doesn't change.
Do you have an idea about this weird error? I suppose that if the user select a file and an app to open it the permission would be granted, but probably I'm missing something. Could you help?

Can't read or create UIManagedDocuments anymore

I have a big issue in my app, which prevents creating new documents and reading them, whereas it worked well until now.
I didn't change anything, and it started bugging from a build to another.
This is the code I'm using:
CLProject *project = [[CLProject alloc] initWithFileURL:projectURL];
NSLog (#"Will save project at URL: %#", projectURL);
[project saveToURL:projectURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
NSLog (#"Project saved: %d", success);
[...]
}];
CLProject is a subclass of UIManagedDocument.
The first NSLog is called, but not the second one. Instead I get an error :
2018-02-14 19:21:03.597495+0100 CamList[2247:750786] Will save project
at URL:
file:///var/mobile/Containers/Data/Application/151E38F5-2214-4876-A188-2AB8B5E8CF6A/Documents/Projects/715A0087-F2EF-439B-A2DD-8E878EF8A973.camlist
2018-02-14 19:21:03.783397+0100 CamList[2247:750886] [default] [ERROR]
Could not get attribute values for item
/var/mobile/Containers/Data/Application/151E38F5-2214-4876-A188-2AB8B5E8CF6A/Documents/Projects/715A0087-F2EF-439B-A2DD-8E878EF8A973.camlist
(n). Error: Error Domain=NSFileProviderInternalErrorDomain Code=1 "The
reader is not permitted to access the URL."
UserInfo={NSLocalizedDescription=The reader is not permitted to access
the URL.}
But it doesn't crash, the app keeps running (but nothing happens because the completion block never gets called).
What I don't understand is that everything was working fine and I haven't changed anything...
Can you help me??
Thanks
Well, it seems to work fine again this morning... Nothing to understand. My iPhone had to be tired...

Unable to read data from Realm file

I want to use realm file with implicit data in my app (In separate project I filled it with data, then made copy of it. Model object is same in both apps).
On simulator, everything is just fine. But when I run app on iPhone, Xcode throws me error.
let path = (NSBundle.mainBundle().pathForResource("testLevel", ofType: "realm"))!
let config = Realm.Configuration(path: path)
let realm = try! Realm(configuration: config) // also tried try! Realm(path: path)
When I print path to .realm file, everything's fine - no nil -
Dont know how to handle it, any ideas? (iOS9)
Error:
fatal error: 'try!' expression unexpectedly raised an error: Error
Domain=io.realm Code=2 "Operation not permitted" UserInfo={Error
Code=2,
NSFilePath=/var/containers/Bundle/Application/7DE151B5-42EE-45C6-8245-B57683EA64D8/sneakers.app/testLevel.realm,
NSLocalizedDescription=Operation not permitted}: file
/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-703.0.18.1/src/swift/stdlib/public/core/ErrorType.swift,
line 54
The Resources folder of your app is read-only, so you can't directly open a writeable Realm file from there.
You'll need to copy it to a directory in which your app has write access (e.g the 'Documents' or 'Application Support' directories) and then try and open it from there. :)

How to share Core Data with multiple Apps (not just an extension) using App Groups and avoid corrupted Core Data stores?

I made an iOS 8 app that uses the new app groups feature to share a Core Data store with an extension. It worked so well that I thought I would try it with 2 separate apps sharing a Core Data store in an App Group container. But while it worked between App and Extension, I am getting Core Data store corruptions issues when sharing with 2 apps.
Depending on the order in which I open the 2 apps, I get different errors:
Fetches cause this error:
CoreData: error: (522) I/O error for database at
/private/var/mobile/Containers/Shared/AppGroup/[…].sqlite. SQLite
error code:522, 'not an error’
Saves cause this error:
CoreData: error: (11) Fatal error. The database at
/private/var/mobile/Containers/Shared/AppGroup/[...].sqlite is
corrupted. SQLite error code:11, 'database disk image is malformed’
Or:
Core Data: error: -executeRequest: encountered exception = error
during SQL execution : PRIMARY KEY must be unique with userInfo = {
NSFilePath = "/private/var/mobile/Containers/Shared/AppGroup/[...].sqlite";
NSSQLiteErrorDomain = 19; } CoreData: error: (19) PRIMARY KEY must be unique
Here's how I did it by creating a framework to hold/manage the database
Add the same entry to your App Groups entitlements in each of your apps
Use it to create your databaseURL using:
[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:
database = [ [UIManagedDocument alloc] initWithFileURL: databaseURL]
[database saveToFileURL: database.fileURL forSaveOperation: UIDocumentSaveForCreating completionHandler: ^(BOOL success)
If successful, initialize the persistentContainer.
Now here's the tricky part... the managedObjectModel has to be defined by the framework. It cannot be in any of the apps. They can see it, but it has to be part of the framework's bundle.
That's the basic outline and there is a lot more to it, but with this you should be able to get there. Have fun!

Resources