Copy files 10.10 Yosemite - macos

I have project with MAgicalRecords and OSX it is convertor SQLITe -> coreData .
Before Yosemite - it worked well but after update - have some troubles
My Steps
[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
//do some workd with save entity }];
than i try to copy database which i get after converting
if ([fileManager fileExistsAtPath:from]) {
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:from];
[fileHandle seekToEndOfFile];
[fileHandle closeFile];
[fileManager copyItemAtPath:from toPath:to error:NULL];
}
BUT file here HAS a tables and colums before copy and his size is 165kb - and after coping NO - he is empty. Does it new feature of MAC ?
As you can see - i put [fileHandle closeFile]; but it still not working.
I noticed that if i close project before copyng file "from" has 1.8mb and has all data.
and there are 3 files
Main.sqlite
Main.sqlite-shm
Main.sqlite-wal
It looks like OS white data in "some memory" but not in file directly.
I try to find solutions but didn find any. Please help

Copying these three files will not fully copy your database. I suggest the answer from this question:
Using MagicalRecord to prepopulate a database (swift). -wal journal created, however, data not copied to database

Thanks it was problem with SQL journal mode
+ (NSDictionary *) getOptionsForCreate {
NSDictionary *pragmaOptions = [NSDictionary dictionaryWithObject:#"MEMORY" forKey:#"journal_mode"];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
pragmaOptions, NSSQLitePragmasOption, nil];
return options;
}
NSPersistentStore *store = [self addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:url
options:[sel getOptionsForCreate]
error:&error];

Related

Cant save image locally IOS8

i have this code working on IOS7, its check if an image exist in device and if not, it download locally.
Now on IOS8 doesnt save nothing, could someone help me?
//folder where save
NSString *ImagesPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
// check if image exist
NSString* foofile = [ImagesPath stringByAppendingPathComponent:nombreImagenLocal];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
// check if image exist locally
if (!fileExists){
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:rutaCompletaLogo]];
//if not, i save it
if (data) {
// url where is saved
NSString *cachedImagePath = [ImagesPath stringByAppendingPathComponent:nombreImagenLocal];
if ([data writeToFile:cachedImagePath atomically:YES]) {
NSLog(#"Downloaded file saved to: %#", cachedImagePath);
}// end
The path to 'Documents' folder has changed from iOS8. Check the Apple tech note
Please, make sure you don't use hardcoded values. Use the methods provided by the API:
NSString *resourcePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
OR (as stated in the previous link)
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
Hope this helps!

How to download file to machine without storing information on iCloud?

How to download file without storing information on iCloud?
My App is the App for downloading pdf to the machine. It was rejected by Apple from the reason that "In particular, we found that after downloading two issues, your app stores 56.5 MB. To check how much data your app is storing: - Go to Settings> iCloud. > Storage & Backup> Manage Storage ". I would like to know how to write if the information is not stored on iClound.
My Script :
- (void) DownloadFile:(NSURL *)url Name:(NSString *)name Folder:(NSString *)folder{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSData *myData = [NSData dataWithContentsOfURL:url];
NSString *file = [NSString stringWithFormat:#"%#/%#",folder,name];
if(![fileManger fileExistsAtPath:file]){
[fileManger createFileAtPath:file contents:myData attributes:nil];
}
}
Just store the PDFs in the application document directory. You can still keep track of which files have been downloaded on which devices by using the iCloud's key-value store. However, the files to be downloaded onto the device would have to come from non-iCloud servers.
You will probably also have to implement a UI for showing which files have been downloaded and which are available and for deleting them from the device if desired.
OH Thank you it complete
#import <sys/xattr.h>
....
-(BOOL) addSkipBackupAttributeToItemAtURL:(NSURL *)URL{
if(&NSURLIsExcludeFromBackupKey == nil){
const char* filePath = [[URL path] fileSystemRepresentation];
const char* attrName = "com.apple.MobileBackup";
u_int8_t attrValue = 1;
int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
return result == 0;
}else{
return [URL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:nil];
}
}
- (void) DownloadFile:(NSURL *)url Name:(NSString *)name Folder:(NSString *)folder{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *curfile = [NSURL fileURLWithPath:folder];
[self addSkipBackupAttributeToItemAtURL:curfile];
NSData *myData = [NSData dataWithContentsOfURL:url];
NSString *file = [NSString stringWithFormat:#"%#/%#",folder,name];
if(![fileManger fileExistsAtPath:file]){
[fileManger createFileAtPath:file contents:myData attributes:nil];
}
}
Thank you

copy and paste text + image from NSPasteboard

we are working on a C++ Qt applciation that copies selected text and/or images from external applications, modifies it and then paste it back. Since we are on Mac, we are doing this part with Objective-C.
We are having problems trying to get an image from the Pasteboard. It works fine for text, but we are not sure about how to handle images or combination of text+image.
Since we dont know what the user might select, we should be able to perform a generic retrieval of content of the pasteboard to modify it and putting it back in the pasteboard.
We've try this:
//we thought about retrieving some generic item from pasteboard, using NSPasteboardItem
NSArray *classes = [[NSArray alloc] initWithObjects:[NSPasteboardItem class], nil];
NSDictionary *options = [NSDictionary dictionary];
NSArray *auxArray = [[NSPasteboard generalPasteboard] readObjectsForClasses:classes options:options];
NSData *archived_data = [auxArray objectAtIndex:0];
Our solution for handling text was:
NSString *text = [[NSPasteoard generalPasteboard] stringForType:NSStringPboardType];
string text_str = string([text UTF8String]);
It didnt work, so, How can we get the user selection from the pasteboard?
We need to get the raw bytes or rtf content in order to modify it as we need, and then putting it back in the pasteboard and paste it back replacing the original user selection.
Thanks!
I think this function will help you
- (IBAction)paste:sender
{
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
NSArray *classArray = [NSArray arrayWithObject:[NSImage class]];
NSDictionary *options = [NSDictionary dictionary];
BOOL ok = [pasteboard canReadObjectForClasses:classArray options:options];
if (ok)
{
NSArray *objectsToPaste = [pasteboard readObjectsForClasses:classArray options:options];
NSImage *image = [objectsToPaste objectAtIndex:0];
[imageView setImage:image];
}
}

A method for 'Save As...' in Core Data app

CD's been an enormous learning curve for me and there's still a bit for me to go, but any help on the following could enable me to lift the current weight on my shoulders!
I'm trying to write a method that implements a "Save As.." for the user in my CD app.
So far I've got:
[saveAsPanel beginSheetModalForWindow:window completionHandler:^(NSInteger userResult)
{
if (userResult == NSOKButton) {
NSPersistentStoreCoordinator *psc = [self persistentStoreCoordinator];
NSURL *oldURL = [self URLOfInternalStore]; //returns the current store's URL
NSURL *newURL = [saveAsPanel URL];
NSError *error = nil;
NSPersistentStore *oldStore = [psc persistentStoreForURL:oldURL];
NSPersistentStore *sqLiteStore = [psc migratePersistentStore:oldStore
toURL:newURL
options:nil
withType:NSXMLStoreType
error:&error];
}
}];
Unfortunately, I just get the error:
Object's persistent store is not reachable from this NSManagedObjectContext's coordinator.
Should I 'remove' and then 'addPersistentStore...' to update it to the new URL? The doc's seem to suggest that all will be handled with in the 'migrate' method.
Thanks in advance!
Edit:
Ok, well, I've come up with my own 'dirty' method. I can imagine that this isn't an approved way of doing things, but there's no error thrown up and the app works as expected at all times (not often I can say that, either!):
-(IBAction)saveAsAction:(id)sender
{
NSSavePanel *saveAsPanel = [NSSavePanel savePanel];
[saveAsPanel beginSheetModalForWindow:window completionHandler:^(NSInteger userResult)
{
if (userResult == NSOKButton) {
[self saveAction:#"saveAsCalling"];
NSURL *newURL = [saveAsPanel URL];
NSError *error = nil;
[[NSFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:internalStore] toURL:newURL error:&error];
//internalStore is a hard-wired NSString that holds the path to the bundle's database
}
}];
}
-(IBAction)loadAction:(id)sender
{
NSOpenPanel *loadPanel = [NSOpenPanel openPanel];
[loadPanel beginSheetModalForWindow:window completionHandler:^(NSInteger userResult)
{
if (userResult == NSOKButton) {
[self saveAction:#"loadCalling"];
NSURL *newURL = [loadPanel URL];
NSURL *oldURL = [NSURL fileURLWithPath:internalStore];
NSError *error = nil;
NSPersistentStoreCoordinator *psc = [SELF_MOC persistentStoreCoordinator];
[psc removePersistentStore:[[self persistentStoreCoordinator] persistentStoreForURL:oldURL] error:&error];
[psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:newURL options:nil error:&error];
[[NSFileManager defaultManager] removeItemAtURL:oldURL error:&error];
[[NSFileManager defaultManager] copyItemAtURL:newURL toURL:oldURL error:&error];
[psc removePersistentStore:[[self persistentStoreCoordinator] persistentStoreForURL:newURL] error:&error];
[psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:oldURL options:nil error:&error];
}
}];
}
The basic reasoning is this: to do a 'SaveAs...' I simply copy out the SQLLite store file in the mainBundle to wherever the user selects and rename it to what they want - as per TechZen's suggestion.
To do a 'Load' then I first removePersistentStore from the bundle's file, add the one that the user's just chosen. Delete the bundle store (which in theory isn't now being used) and then copy the user's choice back into the bundle. Finally, the two operations of remove and addPersistentStore are performed to point the app back to it's bundle's file which is now the user's choice.
Hope that makes sense. If anyone has any thoughts on just how unprofessional a methodology this is then please - be kind as I'm fairly new - let me know. I can't find anything that is more elegant.
I know Apple don't like you using removePersistentStore and addPersistentStore but, as I say no errors are reported (in my actual code I scattered NSLog lines throughout to report what error is holding).
You only use a SaveAs... in a document based app. If you use Core Data as your model, you need to use NSPersistentDocument to save your data. It provide the SaveAs... functionality you seek.
Straight Core Data is used for more database-like apps in which the entire app operates from one data set (more or less.)

Overwriting a file programmatically in Cocoa

This code copies the referenced file and places it in the Docs Directory. I'm trying to build a simple backup solution. The problem is this operation does not overwrite the existing file if the operation is repeated.
Two questions:
What's the best way to overwrite in code?
How difficult would it be to append the current date to each copied file? In this case there would be no overwrite operation. This would be much more useful for keeping incremental backups. If I decide to do it this way I understand I would need to create a new path in order to keep things organized.
Thanks.
Paul
NSString * name = #"testFile";
NSArray * files = [NSArray arrayWithObject: name];
NSWorkspace * ws = [NSWorkspace sharedWorkspace];
[ws performFileOperation: NSWorkspaceCopyOperation
source: #"~/Library/Application Support/testApp"
destination: #"~/Documents/"
files: files
tag: 0];
You could try using NSFileManager, example below (untested):
// Better way to get the Application Support Directory, similar method for Documents Directory
- (NSString *)applicationSupportDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
return [basePath stringByAppendingPathComponent:#"testApp"];
}
- (void) removeFile {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *applicationSupportDirectory = [self applicationSupportDirectory];
NSError *error = nil;
NSString* filePath = [applicationSupportDirectory stringByAppendingPathComponent: #"testFile"];
if ([fileManager fileExistsAtPath:filePath isDirectory:NULL]) {
[fileManager removeItemAtPath:filePath error:&error];
}
}
Edit:
Take a look at the NSFileManager Class Reference for other functions that might be useful (for your second question).

Resources