How to get a `NSURL` of the document directory? - ios

I have the following code:
+(NSURL*) getRecordingDirectory {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSURL* url = [[NSURL alloc] initWithString:documentsDirectory]; //<-- nil
return url;
}
The line NSURL* url = [[NSURL alloc] initWithString:documentsDirectory]; Doesn't seem to work. url remains nil after the line.

You need to use a file URL to get the location of a resource on the file system.
[NSURL fileURLWithPath: documentsDirectory]
You can also use NSFileManager to get the same URL.
NSArray *arr = [[NSFileManager defaultManager] URLsForDirectory: NSDocumentDirectory inDomains: NSUserDomainMask];
NSURL *documentsUrl = [arr firstObject];

Related

Saving and viewing files in iOS

I'm getting base64-encoded file content from server. Then I'm writing data into file. I checked that file is not empty after that, it means data was successfully written to file. But when I'm trying to present this file, all I get is an empty view. So what am I doin' wrong?
enter image description here
[f getFile:^(NSString * _Nonnull string) {
NSString *docsDir;
NSArray *dirPaths;
NSData *content = [string dataUsingEncoding:NSUTF8StringEncoding];
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"hill.jpg"]];
[content writeToFile:databasePath atomically:YES];
if ([[NSFileManager defaultManager] fileExistsAtPath:databasePath]){
NSURL *url = [NSURL fileURLWithPath:databasePath];
UIDocumentInteractionController *documentInteractionController =[UIDocumentInteractionController interactionControllerWithURL:url];
documentInteractionController.delegate = self;
[documentInteractionController presentPreviewAnimated:YES];
}
} Error:^(NSString * _Nonnull errorMessage) {
}];
Edited your code snippet, Try it
[f getFile:^(NSString * _Nonnull string) {
NSString *docsDir;
NSArray *dirPaths;
NSData *content = [[NSData alloc] initWithBase64EncodedString: string options:0];
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:#"hill.jpg"]];
[content writeToFile:databasePath atomically:YES];
if ([[NSFileManager defaultManager] fileExistsAtPath:databasePath]){
NSURL *url = [NSURL fileURLWithPath:databasePath];
UIDocumentInteractionController *documentInteractionController =[UIDocumentInteractionController interactionControllerWithURL:url];
documentInteractionController.delegate = self;
[documentInteractionController presentPreviewAnimated:YES];
}
} Error:^(NSString * _Nonnull errorMessage) {
}];
From your code, I see you save a string into a an image file (hill.jpg). The UIDocumentInteractionController read file base on their extension, so they can't read this file. I think if you change your file name to hill.txt, your code could work. Hope this helps.
As you say, the content gets from the server are base64-encode, so you need to decode it.
NSData *imageContent = [[NSData alloc] initWithBase64EncodedString:string options:kNilOptions];
if (imageContent) {
// save to file
}

AVAudioFile can not read file from document directory

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/audio.mp3",documentsDirectory];
NSURL *audioPathURL = [NSURL fileURLWithPath:filePath];
NSFileManager *filemanager = [[NSFileManager alloc]init];
if ([filemanager fileExistsAtPath:filePath])
{
AVAudioFile *audioFile = [[AVAudioFile alloc] initForReading:audioPathURL error:&err];
}
This can not read the audio file, It returns audioFile nil. For same code when I pass url from NSBundle like
NSString *path = [[NSBundle mainBundle] pathForResource:#"Audio" ofType:#"mp3"];
NSURL *pathURL = [NSURL fileURLWithPath : path];
It works fine, Any sugestions. Thank you
Issue could be the "/" you are using for append filename to path. Try below change
NSString *filePath = [NSString stringWithFormat:#"%#audio.mp3",documentsDirectory];
Or try below alternative:
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"audio.mp3"];
The NSBundle class is used for finds thing in applications bundle, but the Documents directory is outside the bundle, so the way you're generating the path won't work with Documents directory.
Try as below:
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"audio.mp3"];
NSURL *audioPathURL = [NSURL fileURLWithPath:filePath];
NSFileManager *filemanager = [[NSFileManager alloc]init];
if ([filemanager fileExistsAtPath:filePath])
{
AVAudioFile *audioFile = [[AVAudioFile alloc] initForReading:audioPathURL error:&err];
}

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.

Saving many pdf locally on device and retrieving it on click

NSURL *url = [NSURL URLWithString:#"PDFLINK"];
// Get the PDF Data from the url in a NSData Object
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:url];
NSString * name = #"First";
// Store the Data locally as PDF File
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *newFilePath = [documentsDirectory stringByAppendingPathComponent:#"my.pdf"];
NSError *error;
if ([fileManager createFileAtPath:newFilePath contents:pdfData attributes:nil])
{
NSLog(#"Create Sucess");
[self loadPDF];
}
else
{
NSLog(#"Create error: %#", error);
}
}
-(void)loadPDF
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSArray *resultArray = [fileManager subpathsOfDirectoryAtPath:documentsDirectory error:nil];
if (![resultArray containsObject:arrObj])
{
// do something
}
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[resultArray objectAtIndex:0]];
// Now create Request for the file that was saved in your documents folder
//NSLog(#"The filePath %#",filePath);
NSURL *url = [NSURL fileURLWithPath:filePath];
NSLog(#"The url %#",url);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_webView setUserInteractionEnabled:YES];
[_webView setDelegate:self];
[_webView loadRequest:requestObj];
}
Here is my code.I have more 10 pdf and want to store them locally on device and display next time without download.
It saves the pdf again and i cannot check whether it is downloaded or not ?
Please help me
I am not sure what you mean but, to download a file , you need to use NSData:
NSString *stringURL = #"your file URL";
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,#"filename.extension"];
[urlData writeToFile:filePath atomically:YES];
}
Now the downloaded file exists at filePath and you can get it by using:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"filename with extension"];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
you can try this to check if file exists at file path:
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* file = [documentsPath stringByAppendingPathComponent:#"filename"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:file];
if(fileExists){
//dont download, just grab it and display it
}
else{
//download and display it
}

Download and use .txt file in objective-c iphone app

I am having some problems getting my code to work :(
i am trying to download .txt file from the internet and store it in my iphone for further use but it wont work :/
here is my code :
-(void)DownloadFile
{
//declerations
NSString* TheFile;
NSFileManager* FM = [NSFileManager defaultManager];
//downloading file
NSURL *url = [NSURL URLWithString:#"http://www.myfile.com/apple.txt"];
TheFile = [[NSString alloc] initWithContentsOfURL: url
encoding: NSUTF8StringEncoding
error: nil];
//nsstring to nsdata
NSData* data = [TheFile dataUsingEncoding:NSUTF8StringEncoding];
//saving file
[FM createFileAtPath:[DocumentsDir stringByAppendingString:#"/file.txt"] contents:data attributes:nil];
}
DocumentsDir is defined with this function :
-(void)SetDocuments
{
NSArray* doc;
doc = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
DocumentsDir = [doc objectAtIndex:0];
}
Then i use this function assigne the file to a variable:
-(void)SetFile
{
File = [[NSString alloc]
initWithContentsOfFile:[DocumentsDir stringByAppendingString:#"/file.txt"]
encoding:NSUTF8StringEncoding
error:nil];
}
i would appreciate any tips or corrections etc :) thank you for your time.
Change your SetDocuments like this
-(void)SetDocuments{
NSArray* doc;
//doc = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
DocumentsDir = [doc objectAtIndex:0];
}

Resources