Objective C - How to move a file from a location to another? - objective-c

Beginner at Objective C here, I have this code:
//Path of management log file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *urlPath= [documentsDirectory stringByAppendingPathComponent:#"Logs/log.txt"];
NSURL *source = [NSURL fileURLWithPath:urlPath];
//Destination
NSURL * destination = [self.pathControl URL];
//Move file from source to that destination directory.
[[NSFileManager defaultManager] copyItemAtURL:source toURL:destination error:nil];
The problem is that it doesn't do anything. It can compile, but nothing happens. Am I using copyItemAtURL method wrong?

Use to error indicators to understand errors:
NSError *error;
BOOL status = [[NSFileManager defaultManager] copyItemAtURL:source toURL:destination error:&error];
if (status == NO ) {
NSLog(#"errorL %#", error);
}

Related

I want to crete a zip file with multiple images in it and get the entire zip file and send to sftp server

I am trying create a zip file from the contents of another directory in NSdcomentDirectory. I am using "SSZipArchive" for this. But When I try to get the zip file its not available.Here is my code which I am trying.
`
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"/SourceFolder"];
NSString *stringPath2 = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"/ZipFolder"];
//SourceFolder Creation
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
//ZipFolder Creation
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath2 withIntermediateDirectories:NO attributes:nil error:&error];
//Adding Files To SourceFolder
NSData *data = UIImageJPEGRepresentation([UIImage imageNamed:#"flower.jpg"], 1.0);
NSData *data2 = UIImageJPEGRepresentation([UIImage imageNamed:#"Wall.jpg"], 1.0);
[data writeToFile:[stringPath stringByAppendingFormat:#"/image1.jpg"] atomically:YES];
[data2 writeToFile:[stringPath stringByAppendingFormat:#"/image2.jpg"] atomically:YES];
//Retriving Path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *sampleDataPath = [documentsDirectory stringByAppendingPathComponent:#"/SourceFolder"];
NSString *sampleDataPath2 = [documentsDirectory stringByAppendingPathComponent:#"/ZipFolder"];
//To Create ZipFile under /ZipFolder from /SourceFolder
[SSZipArchive createZipFileAtPath: sampleDataPath2 withContentsOfDirectory: sampleDataPath];
//Checking If File exist in source and zip folder
NSFileManager *sharedFileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *files = [sharedFileManager enumeratorAtPath:sampleDataPath]; // The content shows two images which I have added ->image1.jpg,image2.jpg
NSDirectoryEnumerator *files2 = [sharedFileManager enumeratorAtPath:sampleDataPath2]; // However I dont see the .zip file inside it
`
I have below questions:
How can I get the source directory content as a zip file.
How to get the entire zip file so that I can send it to server as zip.
Please help me I am trying from a long time.

Adding sqlite database: No such file or directory

I wan't to add a sqlite file to preload data for my app. I created this file and copied it into the project directory. I added it to Copy Bundle Resources and copy files. But when I wan't to use this file I get an error saying that there is no such file. I would appreciate if anyone could help me.
The code is listed below:
NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"CookBookData" ofType:#"sqlite"]] ;
if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&error]) {
NSLog(#"Couldn't preload data, error: %#", error);
}
The error:
2015-07-29 15:42:34.342 CookBook v1[2897:24912] Couldn't preload data, error: Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)" UserInfo=0x7fe4a35275d0 {NSSourceFilePathErrorKey=/Users/user/Library/Developer/CoreSimulator/Devices/.../data/Containers/Bundle/Application/.../CookBook v1.app/CookBookData.sqlite, NSUserStringVariant=(
Copy
), NSDestinationFilePath=/Users/user/Library/Developer/CoreSimulator/Devices/.../Documents/CookBookModel 2.sqlite, NSFilePath=/Users/user/Library/Developer/CoreSimulator/Devices/.../data/Containers/Bundle/Application/.../CookBook v1.app/CookBookData.sqlite, NSUnderlyingError=0x7fe4a35145d0 "The operation couldn’t be completed. No such file or directory"}
I tried to change my code:
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"CookBookModel3.sqlite"];
NSError *error = nil;
NSString *storePath = [storeURL path];
NSLog(#"Error %#", error);
NSString *dbName = #"CookBookData.sqlite";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentDirectory stringByAppendingString:dbName];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if (!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (success) {
NSLog(#"Success");
}
else{
NSLog(#"Error %#", [error localizedDescription]);
}
}
else {
NSLog(#"Already exists");
}
if (![[NSFileManager defaultManager] copyItemAtPath:dbPath toPath:storePath error:&error]) {
NSLog(#"Couldn't preload data, error: %#", error);
}
But I get another error:
2015-07-30 12:12:29.118 CookBook[29209:208802] Couldn't preload data, error: Error Domain=NSCocoaErrorDomain Code=516 "The operation couldn’t be completed. (Cocoa error 516.)" UserInfo=0x7fe9526318b0 {NSSourceFilePathErrorKey=/Users/user/Library/Developer/CoreSimulator/Devices/DA5D105A-C9AF-4C91-80B3-DFF2C157CC92/data/Containers/Data/Application/BEED2AB9-BFDA-40AC-A8D0-55DD81F9D985/Library/DocumentationCookBookData.sqlite, NSUserStringVariant=(
Copy
), NSDestinationFilePath=/Users/user/Library/Developer/CoreSimulator/Devices/DA5D105A-C9AF-4C91-80B3-DFF2C157CC92/data/Containers/Data/Application/BEED2AB9-BFDA-40AC-A8D0-55DD81F9D985/Documents/CookBookModel3.sqlite, NSFilePath=/Users/user/Library/Developer/CoreSimulator/Devices/DA5D105A-C9AF-4C91-80B3-DFF2C157CC92/data/Containers/Data/Application/BEED2AB9-BFDA-40AC-A8D0-55DD81F9D985/Library/DocumentationCookBookData.sqlite, NSUnderlyingError=0x7fe952610c30 "The operation couldn’t be completed. File exists"}
2015-07-30 12:12:29.121 CookBook[29209:208802] Managed object context
And another variant:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *path = [documentsDir stringByAppendingPathComponent:#"CookBookData.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager copyItemAtPath:path toPath:storePath error:&error];
Use the following to get the paths to the file in question:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *path = [documentsDir stringByAppendingPathComponent:#"CookBookData.sqlite"];
You can then copy the file with the following:
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"database.sqlite"];
[fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
I would include more checking and validation than the above - in particular the fileExistsAtPath: method in NSFileManager.
I hope, this gonna help:
NSError *error;
NSString *dbName = #"CookBookData.sqlite";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentDirectory stringByAppendingString:dbName];
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName];
if ([fileManager fileExistsAtPath:defaultDBPath]) { //check if file exists in NSBundle
BOOL success = [fileManager fileExistsAtPath:dbPath]; // check if exists in document directory
if (!success) {
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error]; //copy to document directory
if (success) {
NSLog(#"Database successfully copied to document directory");
}
else{
NSLog(#"Error %#", [error localizedDescription]);
}
}
else {
NSLog(#"Already exists in document directory");
}
}
else{
NSLog(#"Does not exists in NSBundle");
}
Two things you can check for, go to your document directory of application, check if you can go there and other thing is make sure your sqlite file is properly added to project, you can delete and add again. Let me know, if still there is issue

Save locally generated PDF to app's documents folder in iOS8

It would seem that my apps no longer are able to save files to their documents folder when doing this:
NSString *path = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *dta = [[NSData alloc] init];
dta = [NSData dataWithContentsOfFile:path];
NSLog(#"writing file: %#", path);
if ([dta writeToFile:path options:NSAtomicWrite error:nil] == NO) {
NSLog(#"writeToFile error");
}else {
NSLog(#"Written: %#", path);
[self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path]];
}
I do get "Written" in the log with the full path:
Written: /var/mobile/Containers/Data/Application/ECBCD65D-A990-4758-A07F-ECE48E269278/Documents/9d440408-4758-4219-9c9c-12fe69cf82f2_pdf.pdf
And as long as I don't quit the app I can load the PDF in a UIWebView like this (pdfPath is a string that I pass to the function that loads the PDF file):
[www loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:pdfPath]]];
Any help at all is as always greatly appreciated.
Okay, after mucking about I found that since the documents directory changes path every time I run the app, I had to:
Write the file to the documents folder with the complete path to
the file:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent: fileName];
NSData *dta = [[NSData alloc] init];
dta = [NSData dataWithContentsOfFile:path];
if ([dta writeToFile:path options:NSAtomicWrite error:nil] == NO) {
NSLog(#"writeToFile error");
}else {
NSLog(#"Written: %#", path);
[self addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path]];
}
Save only the file name to my database
Load the file by using the full newly generated Documents directory path and append the file name from my database:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent: pdfPath];

How to save and retrieve files to apps temp folder in ios

I'm new to IOS development. I'm developing an app which involves downloading files and saving that to apps temp folder and I dont know how to do that my current code is given below
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSLog(#"%#",tmpDirURL);
NSString *myString = [tmpDirURL absoluteString];
for(int i=0;i<responseArray.count;i++){
ASIHTTPRequest *saveUrl = [ASIHTTPRequest requestWithURL:responseArray[i]];
[saveUrl setDownloadDestinationPath:myString];
[request startSynchronous];
}
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:myString error:&error];
NSLog(#"%#",directoryContents);
The response array contain a list of URL for downloading files. I know something wrong with my code but I cant find out that error please help me to solve this problem
I found the solution'
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *htmlFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
[data writeToFile:htmlFilePath atomically:YES];
When downloadDestinationPath is set, the result of this request will be downloaded to the file at this location. If downloadDestinationPath is not set, download data will be stored in memory
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSLog(#"%#",tmpDirURL);
NSString *myString = [tmpDirURL absoluteString];
for(int i=0;i<responseArray.count;i++){
ASIHTTPRequest *saveUrl = [ASIHTTPRequest requestWithURL:responseArray[i]];
[saveUrl setDownloadDestinationPath:[myString stringByAppendingPathComponent:[NSString stringWithFormat:#"%i",i ]]; // for each file set a new location inside tmp
[request startSynchronous];
}
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:myString error:&error];
NSLog(#"%#",directoryContents);

Objective-C: EXC_BAD_ACCESS reading NSData from file path

I am trying to read NSData from a file path, and eventually unarchive the data.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
[[NSFileManager defaultManager] createDirectoryAtPath:[docs stringByAppendingString:#"/dynSplash"]
withIntermediateDirectories:NO
attributes:nil
error:nil];
NSString *dynamicSplashFile = [docs stringByAppendingString:#"/dynSplash/dynamicSplash.data"];
DynamicSplash *splash;
if([[NSFileManager defaultManager] fileExistsAtPath:dynamicSplashFile]) {
NSLog(#"Dynamic splash exists");
NSData *data = [NSData dataWithContentsOfFile:dynamicSplashFile];
splash = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
The problem arises on the line [NSData dataWithContentsOfFile:dynamicSplashFile] where a EXC_BAD_ACCESS error is bring thrown.
How can I debug this?