iOS - Saved file missing - ios

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.

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]) {
}

Storing Downloaded PDF To Documents Directory Not Working

I have the following code, I don't want to get into why I am doing it this way, but for some reason this is not working. The stringURL is working fine, it gets data back, but fails to write to the document directory. This is the first time I'm working with files, and have been pulling my hair out trying to get this to work. Please could someone point me in the right direction?
+ (void) downloadAndStorePDFFromURLWithString: (NSString *) stringURL andFileID: (NSString *) fileID andTitle: (NSString *) title;
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *pdfData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: stringURL]];
dispatch_async(dispatch_get_main_queue(), ^(void) {
//STORE THE DATA LOCALLY AS A PDF FILE
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat: #"%#/%#", fileID, title]];
//GET LOCAL FILE PATH OF DOWNLOADED PDF
//NSLog(#"SUCCESSFULLY DOWNLOADED DOCUMENT FOR FILE: %# WILL BE STORED AT %#", fileID, documentsDirectory);
BOOL success = [pdfData writeToFile: documentsDirectory atomically: YES];
NSLog(success ? #"Yes" : #"No");
//TELL TABLEVIEW TO RELOAD
//[[NSNotificationCenter defaultCenter] postNotificationName: #"DocumentDownloaded" object: nil];
//SAVE FILEPATH URL IN NSUSERDEFAULTS
//[PDFDownloadManager addURLToListOfSavedPDFs: [PDFDownloadManager filePath: fileID andTitle: title] andFileID: fileID];
});
});
}
You are attempting to write the file to a subfolder of the Documents folder. This is failing because the subfolder doesn't exist. You need to create the folder before you can write to it.
You should also clean up the code a bit. And use the better NSData method to write the file.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *folder = [documentsDirectory stringByAppendingPathComponent:fileID];
[[NSFileManager defaultManager] createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:nil];
NSString *filePath = [folder stringByAppendingPathComponent:title];
NSError *error = nil;
BOOL success = [pdfData writeToFile:filePath options: NSDataWritingAtomic error:&error];
if (!success) {
NSLog(#"Error writing file to %#: %#", filePath, error);
}

How To Down and store the Text File on Local Cache

I am developing an IOS app..Download data From URL and save on local cache..but i am using this code..first time data can stored in Local cache and also read on the text field..but Delete the app on simulator and run the and again store the text file on local cache..file can't be store..Any help or advice is greatly appreciated. thanks in advance.
NSURL *url = [NSURL URLWithString:#"http://webapp.opaxweb.net/books/"];
NSData *data_file = [[NSData alloc]initWithContentsOfURL:url];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]stringByAppendingPathComponent:#"Documents"]];
NSString *filepath = [resourceDocPath stringByAppendingPathComponent:#"gurugranthsahib.txt"];
[data_file writeToFile:filepath atomically:YES];
NSLog(#"%#",filepath);
NSString* content = [NSString stringWithContentsOfFile:filepath
encoding:NSUTF8StringEncoding
error:NULL];
iOS does not allow writing to the app bundle.
Generally data is written to the Documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
Note:
It is much better practice to use a method call that has an error parameter so when there is an error the error can be examined. In this case you could use:
NSError *error;
BOOL status = [string writeToFile:filePath options:NSDataWritingAtomic error:&error];
if (status == NO) {
NSLog(#"error: %#", error)
}

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

Download a file from a specific link and store it in device iOS?

I am currently working on a iOS application in which I show a download link to download a Excel sheet. I want to save that downloaded file to a location of my iOS device where all my downloaded applications are stored by default, so that I can access it later form my device without opening the application.
Like in android devices, files are stored in my files from where we can access them later on.
Is there any approach to achieve this in iOS.
You can store directly on Document Directory as below
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"tempfile"]]; // It may change according to your need
NSError * error = nil;
[imageData writeToFile:path options:NSDataWritingAtomic error:&error];
Here ,imageData is my data to be write on Document directory
And by saving on Document Directory you can get it from there
NSString * str = "Your Url"
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:str]
cachePolicy:NSURLCacheStorageAllowed
timeoutInterval:20];
NSURLResponse *response;
NSError *error;
NSData * data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
[data writeToFile:filePath atomically:YES];
You can try with it for once
// NSData downloads any file from an URL
NSURL* url = [NSURL URLWithString:#"http://192.168.0.8/PoweredByMacOSX.gif"];
NSData* data = [NSData dataWithContentsOfURL:url];
// get the documents directory
NSArray* pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString* documentsDir = documentsDirectory = [pathArray objectAtIndex:0];
NSString* localFile =
[documentsDir stringByAppendingPathComponent:#"webfile.png"];
// write the downloaded file to documents dir
[data writeToFile:localFile atomically:YES];

Resources