App crash when use nstask with sandbox - sandbox

I used this code in my app:
//create task
NSTask * task=[[NSTask alloc] init];
[task setLaunchPath:#"/bin/ps"];
NSArray * arguments = [NSArray arrayWithObjects: #"axco command,pcpu",nil];
[task setArguments:arguments];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file = [pipe fileHandleForReading];
[task launch];
When I disable the sandbox, it works. But if I enable the sandbox, it crashes with this exception:
NSTask: Task create for path '/bin/ps' failed: 22, "Invalid argument". Terminating temporary process.
Can anyone help me resolve this issue?

Related

Value of type 'FileManager' has no member 'urlsForDirectory' - AppDelegate Swift 3 Error

Since I recently updated to XCode 8 Beta 5 I have been trying to solve this error in my appDelegate Core Data Stack.
In these lines of code I get the following error:
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "fitness.paceapp.Pace" in the application's documents Application Support directory.
let urls = FileManager.default.urlsForDirectory(.documentDirectory, inDomains: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.urlForResource("Dominos", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
Any Ideas on what I could be missing. I am quite lost and there are not many answers out there. Thanks in advance.
Here you go,
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "fitness.paceapp.Pace" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "Dominos", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
It is:
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls.last!
Or
return try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)

Swift Core Data preload persistentStoreCoordinator:

What needs to be modified to preload my sqlite file? I added the file to the project so that makes me think I have to make a change in this code.
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("junkapp.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
//error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
Just change the file url to point to your SQLite file.
You need to
copy the SQLite file from the bundle to the documents directory.
reference this file url in addPersistentStore....
e.g.
// Copying
let path = NSBundle.mainBundle().pathForResource("sqlitefile", ofType:"sqlite")!
let destinationPath =
self.applicationDocumentsDirectory.URLByAppendingPathComponent("junkapp.sqlite")!.path
NSFileManager.defaultManager().copyItemAtPath(
path, toPath: destinationPath, error:nil)
// Using
coordinator!.addPersistentStoreWithType(NSSQLiteStoreType,
configuration: nil, URL: NSURL.fileURLWithPath(destinationPath),
options: nil, error: &error)
This is the final code that worked for me. Note the section //Copying and keep in mind that you will have to delete the app off device or simulator first before running this.
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("junkapp.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
// Copying
let path = NSBundle.mainBundle().pathForResource("junkapp", ofType:"sqlite")!
NSFileManager.defaultManager().copyItemAtPath(path, toPath: url.path!, error:nil)
//end copy
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: NSURL.fileURLWithPath(url.path!), options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
//error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()

Can't read back SQLite file written using -migratePersistentStore withType:NSInMemoryStoreType

(My problem is somewhat similar to this one, except I'm not using an UndoManager, and the proposed solution doesn't work for me.)
My app imports data from a 3rd party app and stores it in memory until the user saves it. The import periodically save:'s to its own managedObjectContext on a background thread. This MOC uses the persistent store coordinator of it's parent NSPersistentDocument MOC. In order to avoid writing to a temp file on disk, a persistent store is added using the type NSInMemoryStoreType. When the user wants to actually save the data to a file on disk, migratePersistentStore withType:NSInMemoryStoreType is called in the writeToURL override in the NSPersistentDocument.
This all works fine as long as I use NSXMLStoreType for writing and reading (at //1 and //2 in the code below).
As soon as I switch to NSSQLiteStoreType, writing does produce a valid SQLite file with all the proper data in it, but reading back the file fails with the following error:
CoreData: error: Encountered exception I/O error for database at /a/b/c.dat. SQLite error code:14, 'unable to open database file' with userInfo {
NSFilePath = "/a/b/c.dat";
NSSQLiteErrorDomain = 14;
} while checking table name from store: <NSSQLiteConnection: 0x6080001e3300>
CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///a/b/c.dat options:{
NSMigratePersistentStoresAutomaticallyOption = 1;
NSReadOnlyPersistentStoreOption = 1;
} ... returned error Error Domain=NSCocoaErrorDomain Code=256 "The file couldn’t be opened." UserInfo=0x60800006df40 {NSSQLiteErrorDomain=14, NSUnderlyingException=I/O error for database at /a/b/c.dat. SQLite error code:14, 'unable to open database file'} with userInfo dictionary {
NSSQLiteErrorDomain = 14;
NSUnderlyingException = "I/O error for database at /a/b/c.dat. SQLite error code:14, 'unable to open database file'";
Here is the relevant simplified code:
// NSPersistentDocument.m
- (BOOL)readFromURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError *__autoreleasing *)error {
NSError *err;
NSDictionary *opts = #{
NSMigratePersistentStoresAutomaticallyOption : #YES,// it doesn't matter if these options are set or not
NSReadOnlyPersistentStoreOption : #YES,
};
if (![self.managedObjectContext.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType //1
configuration:nil
URL:absoluteURL
options:opts
error:&err])
{
return NO;
} else {
return YES;
}
}
- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation originalContentsURL:(NSURL *)absoluteOriginalContentsURL error:(NSError *__autoreleasing *)error {
NSDictionary *opts = #{
NSMigratePersistentStoresAutomaticallyOption : #YES,// it doesn't matter if these options are set or not
NSReadOnlyPersistentStoreOption : #YES,
};
NSError *err;
[self.managedObjectContext.persistentStoreCoordinator migratePersistentStore:self.managedObjectContext.persistentStoreCoordinator.persistentStores[0]
toURL:absoluteURL
options:opts
withType:NSSQLiteStoreType //2
error:&err];
return YES;
}
// ====================================
// NSOperation.m
- (void)main
{
[...]
self.managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
self.managedObjectContext.persistentStoreCoordinator = self.myDoc.managedObjectContext.persistentStoreCoordinator;
self.managedObjectContext.undoManager = nil;
[self.managedObjectContext.persistentStoreCoordinator addPersistentStoreWithType:NSInMemoryStoreType
configuration:nil
URL:nil
options:nil
error:nil];
A typical database consists of 30k objects which takes ages to write and read when using XML so I do need to use the SQLite type.
Any suggestions are welcome.
I solved the problem by using the following dict in the -writeToUrl method:
NSDictionary *opts = #{NSSQLitePragmasOption: #{#"journal_mode":#"DELETE"}};

Swift crashing with two core data entities

I have an app set up with core data and one entity named "subject", when I try to add another entity to core data called "homework", my app crashes and I get this error
2014-10-04 12:41:05.302 HomeJournal[1050:20160] Unresolved error Optional(Error Domain=YOUR_ERROR_DOMAIN Code=9999 "Failed to initialize the application's saved data" UserInfo=0x7fe6bb60cac0 {NSLocalizedFailureReason=There was an error creating or loading the application's saved data., NSLocalizedDescription=Failed to initialize the application's saved data, NSUnderlyingError=0x7fe6bb524760 "The operation couldn’t be completed. (Cocoa error 134100.)"}), Optional([NSLocalizedFailureReason: There was an error creating or loading the application's saved data., NSLocalizedDescription: Failed to initialize the application's saved data, NSUnderlyingError: Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x7fe6bb524720 {metadata={
NSPersistenceFrameworkVersion = 519;
NSStoreModelVersionHashes = {
Subject = <e90676da 933291ac ffe738ee ec80ba71 d2cc14a0 df80b9fe b69b358c 43d4cebc>;
};
NSStoreModelVersionHashesVersion = 3;
NSStoreModelVersionIdentifiers = (
""
);
NSStoreType = SQLite;
NSStoreUUID = "CB1FC120-99D2-4DB2-9C08-D6679CC6ECB7";
"_NSAutoVacuumLevel" = 2;
}, reason=The model used to open the store is incompatible with the one used to create the store}])
(lldb)
I'm not sure what I did wrong, I have it set up to get the data out of the entity called "subject" using this code
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Subject")
request.returnsObjectsAsFaults = false;
Which works perfectly if there is only one entity.
Thanks in advanced
As someone suggested in comment, try deleting the app from simulator and re-install. If it still fails then match the NSManagedObject files you created for your data models to that in actual data models. It may be the case that you created files and then changed the models.

'The specified persistent store was not found.' error in CoreData

I'm getting this error:
The operation couldn’t be completed. (Cocoa error 134140.)
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The specified persistent store was not found.'
I just changed to a new version of my data model. However if I activate the previous version of the data model, then the app works fine. If I activate the new version, I get that error. The only change that I made was that I made all the variables non-optional in my data model, which should be able to be handled by the automatic migration feature. I don't understand why it says it cannot find the persistent store, when there is no error thrown by [fileManager copyItemAtPath:defaultStorePath toPath:myPathDocs error:&error].
I seem to think this has something to do with the fact that the sqlite file in my main bundle is from the old version of the data model, but there is no sqlite file there that comes from the new version. However, I was under the impression that automatic migration would simply generate a new file for the new model on its own (?) and migrate the data from the existing file into it. Is this wrong?
In my iOS app, I have a file called Formats.sqlite that's in my Resources. At startup after a clean install the app looks to see if there's an existing Formats.sqlite in the app's /Documents folder. If there's not, it copies the one from its main bundle into there. This was all working fine before I made the new version of my model. Here is the code I use for that:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
int count = [[persistentStoreCoordinator persistentStores] count];
if (persistentStoreCoordinator != nil && count) {
return persistentStoreCoordinator;
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:#"Formats.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileManager fileExistsAtPath:myPathDocs]) {
NSLog(#"SQLite file not found, copying SQLITE file");
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:#"Formats" ofType:#"sqlite"];
if (defaultStorePath) {
if(![fileManager copyItemAtPath:defaultStorePath toPath:myPathDocs error:&error]) {
NSLog(#"Error copying file at defaultStorePath to the documents path: %#",error);
}
}
}
storeURL = [NSURL fileURLWithPath:myPathDocs];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
if (persistentStoreCoordinator == nil) {
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
}
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{//my error code here}
So then the error gets thrown where it says "my error code here." What do I do in order to fix this? Why is this happening? Incidentally the console spits out all the steps for the migration, so it looks like it's trying to do it, but then it can't find the persistent store, which I don't understand why it can't find it, since it's been added in the build targets.
I just want to make sure that if people upgrade from previous versions of the app, their data gets migrated over and they don't have to re-enter everything. Thanks!
To find the source of the error, I used this code to get the most detailed description of the error from the debugger:
NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
if(detailedErrors != nil && [detailedErrors count] > 0) {
for(NSError* detailedError in detailedErrors) {
NSLog(#" DetailedError: %#", [detailedError userInfo]);
}
} else {
NSLog(#" %#", [error userInfo]);
}
Then after using that code, the error message said that one of the properties in my model did not have a default value, and that it would need one for the automatic migration to work correctly. After I added the default value for that property, then everything worked.
The above code snippet is very useful for debugging Core Data errors because without it, Core Data won't necessarily tell you which exact property in your model is the source of the problem. Using the "detailedError" code gave me the exact info I needed. Thanks, "detailedError."

Resources