How To Down and store the Text File on Local Cache - ios

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

Related

How to check if a file is download?

How can I check if a file is download and save on device? Help me please.
- (void) song{
if (_index1 == 0) {
NSString *stringURL = #"https://drive.google.com/uc?export=download&id=0B0EJbcHq3ZALWUo0a05LMWNzeDg";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"music.mp3"];
[urlData writeToFile:filePath atomically:YES];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:nil];
}
}
}
If you want to see if the file music.mp3 is in your Documents folder:
NSString *filePath = [documentsDirectory stringByAppendingPathComponent#"music.mp3"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
This only makes sense if that file is always the same file. If it can be different files then you need to associate the URL you use to download with the file you stored it in.

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

Unable to download/read a file in documents path of my ios app

I am using the below code to download a ebook from url and store into my device. While this works in emulator, in my ipad I am getting error saying file is not available. I am not able to read the file in the respective path of the device. please help..
NSString *urls = [NSString stringWithFormat: #"http://hungerin.com/?download_file=%#&order=%#&email=%#&key=%#", BookID, orderKey, email, downloadId];
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: urls]];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#""]];
NSString *filePathAppend = [NSString stringWithFormat: #"/testPubb.app/Documents/%#.epub",BookID];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:filePathAppend];
[pdfData writeToFile:filePath atomically:YES];
The way you are getting the app document directory path is not correct. Try this:
NSString *urls = [NSString stringWithFormat: #"http://hungerin.com/?download_file=%#&order=%#&email=%#&key=%#", BookID, orderKey, email, downloadId];
NSData *pdfData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urls]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.epub",BookID];
[pdfData writeToFile:filePath atomically:YES];
Let me know if you have questions.

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];

How to store JSON data in a file?

I am building an article reading iOS app.
I have a .json file in match folder named as Data.json
I am not able to write data into it.
Here is my code:
- (void)writeJsonToFile {
//applications Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//live json data url
NSString *stringURL = ysURL;
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
//file to write to
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, #"Data.json"];
//attempt to download live data
if (urlData) {
[urlData writeToFile:filePath atomically:YES];
}
//copy data from initial package into the applications Documents folder
else {
//file to write to
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, #"Data.json"];
//file to copy from
NSString *json = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"json" inDirectory:#"/match/Data.json"];
NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];
//write file to device
[jsonData writeToFile:filePath atomically:YES];
}
}
Try using NSStrings method to write the file, and check your error code:
NSURL *fileUrl = [[NSBundle mainBundle] URLForResource: #"Data" withExtension:#"json"];
NSError * error;
[json writeToURL:fileUrl atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#",error.localizedDescription);
can you tell us more about the problem you have ?
1) You don't have to redefine the filePath in the else because you already did before.
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, #"Data.json"];
And you should use stringByAppendingPathComponent which automaticaly add the / you will need or not :
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Data.json]
2) Are you sure your Data.json is include in your project ? do you get a nil ?
NSString *json = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"json" inDirectory:#"/match/Data.json"];
3) For the problem of not load : </Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.pl​atform/Developer/SDKs/iPhoneSimulator7.1.sdk/System/Library/AccessibilityBundles/CertUIFramework.axbundle> (not loaded)
Cannot find executable for CFBundle CertUIFramework.axbundle

Resources