How to check if file saved successfully in objective-c - ios

In my app i use the below code to wirte a .db file to Documents Directory and then want to use it
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",str);
NSMutableDictionary *retval = [json objectWithString:str];
if ([[retval objectForKey:#"Success"] boolValue])
{
NSString *downloadedData=[[retval objectForKey:#"Value"] objectForKey:#"SqLiteFileArray"];
NSData *mydata=[NSData dataWithBase64EncodedString :downloadedData];
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir=[paths objectAtIndex:0];
NSString *documentFile=[documentDir stringByAppendingPathComponent:#"4_program.db"];
NSString * yourAppendingText=[[NSString alloc]initWithData:mydata encoding:NSUTF8StringEncoding];
[yourAppendingText writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSLog(#"finish");
//[self getfile];
//NSLog(#"data %#",downloadedData);
}
else
{
NSLog(#"aaa");
}
self.view.userInteractionEnabled = TRUE;
}];
in nslog i see the finish statement so i thought the file written successfully
but when i re-enter to the app and check if file exists in documents directory it says it is not there
this is my file exists code:
NSString *docsDir;
NSString *realpath;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
realpath=[[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent: #"4_program.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: realpath ] == NO)
{
NSLog(#"no file");
}
else
{
NSLog(#"file found");
[self getdata];
}
am i missing something? how can i learn file written successfully finished?

i changed to my writeToFile to
[[NSFileManager defaultManager] createFileAtPath:documentFile
contents:mydata
attributes:nil];
and now it works and everything is ok

Related

NSString to PDF file - iOS

I'm receiving a String from a web service and I would like to store it as a pdf file.
I know the have asked before but the answer is always the same. I've tryed it and didn't worked, and it's not explained enough.
So, this is what I'm doing:
NSData *data = [documentString dataUsingEncoding:NSUTF8StringEncoding];
NSString *formattedName = [NSString stringWithFormat:#"%#.pdf", name];
NSString *pdfPath = [#"documents/" stringByAppendingPathComponent:formattedName];
NSError *error = nil;
if([data writeToFile:pdfPath options:NSDataWritingAtomic error:&error]) {
}
It's not entering in the if, and I think the file is not being generated.
I'm working with objective-c, xcode 9.
What should I modify?
Create it
NSError*error=nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"/Application Support"];
NSString*filePathC = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"historyImages"]];
if(![[NSFileManager defaultManager]fileExistsAtPath:filePathC])
{
if(
[[NSFileManager defaultManager] createDirectoryAtPath:filePathC
withIntermediateDirectories:YES
attributes:nil
error:&error])
{
NSLog(#"created");
}
else
{
NSLog(#"not created");
}
}
else
{
NSLog(#"exists");
}
///
NSData *data = [documentString dataUsingEncoding:NSUTF8StringEncoding];
NSString *formattedName = [NSString stringWithFormat:#"%#.pdf", name];
NSString *pdfPath = [filePathC stringByAppendingPathComponent:formattedName];
NSError *error2 = nil;
if([data writeToFile:pdfPath options:NSDataWritingAtomic error:&error2]) {
}

ios - cannot decrypt after encryption

I'm having troubles decrypting pdf files and displaying them with presentViewController after they are encrypted.
When I download the pdf files, they are being encrypted like this:
NSData *pdfData = [[NSFileManager defaultManager] contentsAtPath:filePathDocumetFolder];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString *docFolder = [NSString stringWithFormat:#"/Documents/%#", documentFilePath];
NSString *filePath = [documents stringByAppendingPathComponent:docFolder];
NSString *pdfName = [NSString stringWithString:filename ];
NSError *error;
NSData *encryptedPdf = [RNEncryptor encryptData:pdfData withSettings:kRNCryptorAES256Settings password:#"A_SECRET_PASSWORD" error:&error];
if(error){
NSLog(#"error: %#", error);
}
NSLog(#"where?? FileTra%#", filePath);
[encryptedPdf writeToFile:[filePath stringByAppendingPathComponent:pdfName] atomically:YES];
I know that this encryption above works, as when I browse the filesystem with iExplorer, I cannot open the files because they are protected.
In my DocumentHandle controller I'm trying to decrypt them so that they can be viewed:
NSDictionary* dict = [command.arguments objectAtIndex:0];
NSString* urlStr = dict[#"url"];
NSURL* url = [NSURL URLWithString:urlStr];
NSString* fileName = [url path];
NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent: fileName];
NSData *dataEn = [[NSFileManager defaultManager] contentsAtPath:[path stringByAppendingPathComponent:fileName]];
NSLog(#"this to decrypt%#", [path stringByAppendingPathComponent:fileName]);
NSData *decryp = [RNDecryptor decryptData:dataEn withSettings:kRNCryptorAES256Settings password:#"A_SECRET_PASSWORD" error:nil];
[decryp writeToURL:[[NSURL alloc] initFileURLWithPath:path] atomically:YES];
if(decryp){
NSLog(#"decrypted");
}else{
NSLog(#" not decrypted");
}
weakSelf.fileUrl = [[NSURL alloc] initFileURLWithPath:path];
For some reason, the pdf files are not being decrypted and I'm being presented with a blank file even thought I'm receiving NSLog as decrypted :(
Can anyone help me please? thank you

iOS - Saved file missing

I tried saving a file into NSLibraryDirectory with the below code:
if (!userDir) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
documentsDirectory = [[[documentsDirectory stringByAppendingPathComponent:#"Caches"] stringByAppendingPathComponent:#"account"] stringByAppendingPathComponent:#"test"];
NSString *imageDir = [[documentsDirectory stringByAppendingPathComponent:#"Root"] stringByAppendingPathComponent:#"imageType"];
NSError *error = nil;
BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:imageDir withIntermediateDirectories:YES attributes:nil error:&error];
NSString *fileName = #"avatar"
NSString filePath = [imageDir stringByAppendingPathComponent:fileName];
}
NSData *imagedata = **imagedata**
NSError *saveError = nil;
[imageData writeToFile:filePath options:NSDataWritingWithoutOverwriting error:&saveError];
Image is saved and I can load it using the following method:
NSError *error = nil;
NSData *imageData = [[NSData alloc] initWithContentsOfFile:filePath options:NSDataReadingUncached error:&error];
When I kill the app and launch it again, the file is missing. Am I doing anything wrong here?
You're saving it in the Caches directory, which the system may clear whenever your app is not running. If you want the file to stick around more permanently you should store it somewhere else, like the Documents directory.

Create a file to an application document folder

I want to create a file in my application document folder and i have to store some content. That content takes from my localhost file. So i write a below code. But this code didn't create a file in my application document folder.
- (void) createFile
{
NSString *strPath = [NSString stringWithFormat:#"http://192.168.5.117/~mac/banana.obj"];
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:strPath]];
NSString *strLastpath = [strPath lastPathComponent];
NSString *folderName = [#"Object File/" stringByAppendingString:strLastpath];
NSLog(#"Path : %# \n File Name : %#",strPath,folderName);
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:folderName]];
NSLog(#"Database Path : %#",databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:databasePath] == YES)
{
NSLog(#"File Exists");
}
else
{
NSLog(#"File not exists");
}
NSString *content = [NSString stringWithFormat:#"%#",data];
[content writeToFile:strLastpath atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
}
While build for running i got this.
2013-10-11 11:36:38.833 SampleFileCreation[1321:c07] Path : http://192.168.5.117/~mac/banana.obj
File Name : Object File/banana.obj
2013-10-11 11:36:38.834 SampleFileCreation[1321:c07] Database Path : /Users/mac/Library/Application Support/iPhone Simulator/6.1/Applications/4FA749DF-D12D-4956-AF76-140D2F981F17/Documents/Object File/banana.obj
2013-10-11 11:36:38.834 SampleFileCreation[1321:c07] File not exists
You can also try this code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *fileName = #"yourFileName";
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/fileName"];
NSDate *data = [NSData dataWithContentsOfURL:YourUrl]; // get date form url
[data writeToFile:dataPath atomically:YES]; // save data in file
I found the answer. File created successfully.
- (void) createFile {
NSString *strPath = [NSString stringWithFormat:#"http://-.-.-.-/~mac/banana.obj"];
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:strPath]];
NSString *strLastpath = [strPath lastPathComponent];
NSString *folderName = [#"Object File/" stringByAppendingString:strLastpath];
NSLog(#"Path : %# \n File Name : %#",strPath,folderName);
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
docsDir=[docsDir stringByAppendingString:#"/Object File"];
databasePath = [[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent:folderName]];
NSLog(#"Database Path : %#",databasePath);
NSError *theError = nil;
NSFileManager *filemgr = [NSFileManager defaultManager];
**//I added this line**
[filemgr createDirectoryAtPath:docsDir
withIntermediateDirectories:YES
attributes:nil
error:&theError];
**//Changed this line**
[data writeToFile:[docsDir stringByAppendingPathComponent:strLastpath]
options:NSDataWritingAtomic
error:&theError];
if ([filemgr fileExistsAtPath:[docsDir stringByAppendingPathComponent:strLastpath]]){
NSLog(#"File Exists");
} else {
NSLog(#"File not exists");
NSLog(#"Tell Me error %#",[theError localizedDescription]);
}
}

iOS download sqlite database and replace existing one

I have to download the database and replace existing one in the sandbox:
Here's is the presumable way to do that:
DBHelpers *help=[[DBHelpers alloc] init];
NSString *targetPath=[[help DocumentsDirectory] stringByAppendingPathComponent:DATABASE_NAME];
NSLog(#"Target path: %#", targetPath);
NSFileManager *fileManager=[NSFileManager defaultManager];
//if([fileManager fileExistsAtPath:targetPath])
//{
// NSLog(#"Exists");
// return;
}
NSString *sourcePath=[help PathForResource:DATABASE_NAME];
NSLog(#"SourcePath path: %#", sourcePath);
NSError *error;
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:#"www.hello.com/mydb.sqlite"]];
[data writeToFile:targetPath atomically:NO];
// [fileManager copyItemAtPath:sourcePath toPath:targetPath error:&error];
NSLog(#"Error %#", error);
Consider these steps:
NSData *fetchedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.myserver.com/files/DBName.sqlite"]]];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDire ctory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"DBName.sqlite"];
[fetchedData writeToFile:filePath atomically:YES];
from iphonedevsdk forum thread.

Resources