I want to download a file(pdf, doc, docx etc) in NSFileManager from some specific URL. Later on when user taps on same link I want to retrieve the file from NSFileManager. Here is the code I've done:
- (void)checkIfFileExist {
NSString *path1;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path1 = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Content-Directory"];
path1 = [path1 stringByAppendingPathComponent:#"sample.pdf"];
NSLog(#"The read path is %#", path1);
if ([[NSFileManager defaultManager] fileExistsAtPath:path1])
{
//File exists
NSData *file1 = [[NSData alloc] initWithContentsOfFile:path1];
if (file1)
{
}
}
else
{
NSURL *url = [NSURL URLWithString:#"http://fzs.sve-mo.ba/sites/default/files/dokumenti-vijesti/sample.pdf"];
NSData *urlData = [NSData dataWithContentsOfURL:url];
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Content-Directory"];
path = [path stringByAppendingPathComponent:#"sample.pdf"];
NSLog(#"The written path is %#", path);
[[NSFileManager defaultManager] createFileAtPath:path
contents:urlData
attributes:nil];
}
}
Now here every time I'm trying to fetch the file from file manager the condition that file exists always returning me FALSE. The paths where I'm writing and reading the file are same as I've checked them on console. Any mistake that I've done?
Add this
if (![[NSFileManager defaultManager] fileExistsAtPath:path]){[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];}
after
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Content-Directory"];
in your else part and replace
[[NSFileManager defaultManager] createFileAtPath:path contents:urlData attributes:nil];` with `[urlData writeToFile:path atomically:YES];
Related
I need to create a folder and files in this path
/var/mobile/Containers/Data/
but when I look for it can't find the folder
my code >>
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = #"/var/mobile/Containers";//[paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"MyNewFolder/myDB.db"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
I dint really understood your problem . Hope this helps :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(#"Saving");
NSUserDefaults *prefs = [[NSUserDefaults alloc] init];
NSString *path1 = [NSString stringWithFormat:#"/var/mobile/Containers"];
NSString *dataPath = [path stringByAppendingPathComponent:path1];
dataPath = [dataPath stringByStandardizingPath];
filePath = [dataPath stringByAppendingPathComponent:#"MyNewFolder/myDB.db"];
Here's the iOS 8 approach Apple recommends to retrieve the location of the Documents directory:
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
Create Folder
//-- to select path from image--//
AppDelegate *del = (AppDelegate*)[[UIApplication sharedApplication]delegate];
NSString *dataPath=[del.databasePath copy];
NSString *Documentpath=[del.path_Folder_Document copy];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Fetch path for document directory
dataPath = (NSMutableString *)[documentsDirectory stringByAppendingPathComponent:#"/Images"];
Pathforimage=dataPath;
Add Folder if not Exist
if (![[NSFileManager defaultManager] createDirectoryAtPath:Pathforimage withIntermediateDirectories:NO attributes:nil error:nil])
{
//NSLog(#"directory... /Images already exist..");
}
else
{
//NSLog(#"directory created!");
}
NSString *pathforAudios=[NSString stringWithFormat:#"%#/Images_Audio",Documentpath];
if (![[NSFileManager defaultManager] createDirectoryAtPath:pathforAudios withIntermediateDirectories:NO attributes:nil error:nil])
{
//NSLog(#"directory... /Images already exist..");
}
else
{
//NSLog(#"directory created!");
}
//-- end of path --//
Save Image to Folder
//Save Image to Documents Directory
NSString *imagePath = [Pathforimage stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.jpg",Img_File_Name]];
[UIImageJPEGRepresentation(image, 0.1) writeToFile:imagePath atomically:YES];
imagePath=nil;
image=nil;
Delete Files/Folder
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files =%#",files);
NSString *Images_Folder = (NSMutableString *)[documentsDirectory stringByAppendingPathComponent:#"/Images"];
NSArray *fileArray = [fileMgr contentsOfDirectoryAtPath:Images_Folder error:nil];
for (NSString *filename in fileArray)
{
NSLog(#"Images =%#",filename);
[fileMgr removeItemAtPath:[Images_Folder stringByAppendingPathComponent:filename] error:NULL];
}
NSString *Images_Audio_Folder = (NSMutableString *)[documentsDirectory stringByAppendingPathComponent:#"/Images_Audio"];
NSArray *fileArray1 = [fileMgr contentsOfDirectoryAtPath:Images_Audio_Folder error:nil];
for (NSString *filename in fileArray1)
{
NSLog(#"Images_Audio =%#",filename);
[fileMgr removeItemAtPath:[Images_Audio_Folder stringByAppendingPathComponent:filename] error:NULL];
}
Create floder
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyNewFolder"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:dataPath]){
[fileManager createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&error]; //Create folder
}else{
NSLog(#"exist");
}
NSLog(#"dataPath:%#",dataPath);
I am creating a directory inside my application.Is there a code to view the contents of the directory in xcode. For example in android you can create a custom directory and view its contents using a file manager application. Can the similar procedure be done in apple?
Here is the code which i use to create a directory?
bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
fileManager = [NSFileManager defaultManager];
myImageDirectory = [fileManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask];
if ([myImageDirectory count] == 1){
NSLog(#"myImageDirectoryIs already present directory is already present");
}else{
directoryPath = [[myImageDirectory objectAtIndex:0] URLByAppendingPathComponent:bundleIdentifier];
NSLog(#"myImageDirectory directory name = %#",[directoryPath absoluteString]);
NSError *theError = nil;
if (![fileManager createDirectoryAtURL:directoryPath withIntermediateDirectories:NO attributes:nil error:&theError]){
NSLog(#"didnt write image data");
}else{
imagePath = [[directoryPath absoluteString] stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#_%#_%#_image.jpg",dIdNo,iIdNo,[self currentDateandTime]]];
[imageData writeToFile:imagePath atomically:YES];
}
}
If your app is running in the simulator you'll need to use Finder. Go to the following directory:
/Users/<username>/Library/Application Support/iPhone Simulator/<iOS version>/Applications/<uuid>/Library/Application Support
If your app is running on the device you can use Xcode:
Connect the device
Choose menu option Window -> Organizer
Go to the Devices Tab
Click Applications under the device menu on the left
Pick your Application
The directory contents will be listed and you can optionally download everything.
try this...
to create a directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
to retrieve contents from directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *customDirectory = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
NSError * error;
NSArray *directoryContents = [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:customDirectory error:&error];
for(NSString *strFile in directoryContents)
{
NSString *strVideoPath = [NSString stringWithFormat:#"%#/%#",customDirectory,strFile];
if([[strVideoPath pathExtension] isEqualToString:#"mp4"] || [[strVideoPath pathExtension] isEqualToString:#"mov"])
{
[urlArray addObject:strVideoPath];
}
}
you can get the contents of the directory(MYNewFolder) from below code:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"MYNewFolder"];
NSArray *filePathsArray = [[NSFileManager defaultManager]
subpathsOfDirectoryAtPath:stringPath
error:nil];
for ( NSString *apath in filePathsArray )
{
NSLog(#"inside the file path array=%d",apath);
}
Method
-(NSArray *) getObjectsInDirectory:(NSString *)directory {
NSFileManager * fm = [NSFileManager defaultManager];
NSError * error = nil;
NSArray * result = [fm contentsOfDirectoryAtPath:directory error:&error];
return result;
}
How-To
NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray * files = [self getobjectsInDirectory:documentsPath];
This code is used to get an array of the files within the documents directory.
Viewing the Files
NSLog(#"%#", files);
Check this class out, it allows you to simplify so many things in iOS: Atomic Class
This is the code I'm using and it works in simulator but showing nothing in idevice. If I add an folder or a file through ifunbox it shows up in device though. Do I need any permission to create or add files?
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"/Folders/%#", self.txtFolder.text]];
NSLog(#"%#", dataPath);
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
[sec1Contents addObject:self.txtFolder.text];
sec1 = [NSArray arrayWithArray:sec1Contents];
[self.tblFiles reloadData];
}
thanks in advance.
Use this code :
NSURL *allitemsImageurl =[NSURL URLWithString: url];
NSData *allItemsImageData = data1; // Load XML data from web
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectoryPath = [paths objectAtIndex:0];
NSString *st1=[ #"img_" stringByAppendingString:[NSString stringWithFormat:#"%d.png",imageCount]];
NSString *allitemsImagePath = [documentsDirectoryPath stringByAppendingPathComponent:st1];
NSLog(#"%#",allitemsImagePath);
[allItemsImageData writeToFile:allitemsImagePath atomically:TRUE];
I am using the code
NSArray *directoryNames = [NSArray arrayWithObjects:#"hats",#"bottoms",#"right",#"left",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
for (int i = 0; i < [directoryNames count] ; i++) {
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:i]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:#"hats"]; // "right" is at index 2, per comments & code
NSString *filePath = [folderPath stringByAppendingPathComponent:#"IMAGE_NAME_HERE.PNG"];
NSData *imageData = UIImagePNGRepresentation(captureImage.image);
[imageData writeToFile:filePath atomically:YES];
}
to save however it always replaces itself so I can't save multiple photo's. How should I make it so that it will stop doing that without duplicating itself?
You're always saving to the same place, per this code:
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:#"hats"]; // "right" is at index 2, per comments & code
NSString *filePath = [folderPath stringByAppendingPathComponent:#"IMAGE_NAME_HERE.PNG"];
NSData *imageData = UIImagePNGRepresentation(captureImage.image);
[imageData writeToFile:filePath atomically:YES];
Looping through the array just saves everything to the 'hats' path every time. You're already calculating the place to store the image based on the array object, through the dataPath object. You just aren't doing anything with that. Instead, do this:
for (int i = 0; i < [directoryNames count] ; i++) {
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:i]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder
[imageData writeToFile:dataPath atomically:YES];
}
II have created multiple directories like this
NSArray *directoryNames = [NSArray arrayWithObjects:#"hats",#"bottoms",#"right",#"left",nil];
however I do not know how to save into a specific directory.I save like this
NSString *filePath = [folderPath stringByAppendingPathComponent:#"IMAGE_NAME_HERE.PNG"];
NSData *imageData = UIImagePNGRepresentation(captureImage.image);
[imageData writeToFile:filePath atomically:YES];
However I do not know how to specify the directory. I only want the user to save into directory hats. How can I do this?
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *imageCacheDirPath = [docsPath stringByAppendingPathComponent:#"hats"];
NSString *imageCachePath = [imageCacheDirPath stringByAppendingPathComponent:#"IMAGE_NAME_HERE.PNG"];
if (![[NSFileManager defaultManager] fileExistsAtPath: imageCacheDirPath])
[[NSFileManager defaultManager] createDirectoryAtPath:imageCacheDirPath
withIntermediateDirectories:NO
attributes:nil
error:NULL];
[[NSFileManager defaultManager] createFileAtPath:imageCachePath
contents:dataObj
attributes:nil];