My folder contains only one sub-folder, and I don't know sub-folder's name. This sub-folder contains a html file, and once again I don't know the html file's name.
My question is how I can get full path of this file by using
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:filename];
//- access sub-folder?
//- access html file?
EDITED:
I wrote a method to return the only one sub-folder as follow:
+ (NSString*) get1stSubFolder:(NSString*)folder
{
NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:folder];
//- no recursive
[directoryEnumerator skipDescendents];
NSString* file;
while (file = [directoryEnumerator nextObject])
{
BOOL isDirectory = NO;
BOOL subFileExists = [[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDirectory];
if (subFileExists && !isDirectory) {
return file;
}
}
return nil;
}
I always get nil as result. Do you know where was I wrong at?
Use NSDirectoryEnumerator. It should help you.
Use NSDirectoryEnumerator like this.
NSURL *documentsDirectoryURL = [NSURL URLWithString:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] ];
///If the folder you want to browse for subfolders is NSDocumentDirectory.
NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];
NSDirectoryEnumerator *enumerator = [[[NSFileManager alloc] init]
enumeratorAtURL:documentsDirectoryURL
includingPropertiesForKeys:keys
options:0
errorHandler:^(NSURL *url, NSError *error) {
return YES;
}];
for (NSURL *url in enumerator) {
NSError *error;
NSNumber *isDirectory = nil;
if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
NSLog(#"Error %#",error);
}
else if ([isDirectory boolValue]) {
NSLog(#"Folder URL: %#",url);
}else{
NSLog(#"File URL: %#",url);
}
}
Related
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]) {
}
I am trying to save and retrieve a file from a folder in the documents directory. I retrieve it in this way:
NSFileManager *fManager = [NSFileManager defaultManager];
NSString *item;
NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSArray *contents = [fManager contentsOfDirectoryAtPath:[NSString stringWithFormat:#"%#", docsPath] error:nil];
and save it like this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* BusinessCardPath = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:#"BusinessCard%lld.card", arc4random() % 100000000000000]];
For some reason if I do:
NSArray *contents = [fManager contentsOfDirectoryAtPath:[NSString stringWithFormat:#"%#/FOLDER", docsPath] error:nil];
and
NSString* BusinessCardPath = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:#"FOLDER/BusinessCard%lld.card", FolderNumber, arc4random() % 100000000000000]];
It doesn't open or show the file, but when I log the two it shows the same directory. Is this how you use folders in IOS? Please help, i'm going crazyyyy!!
I guess you use the NSFileManager for nothing. it's confusing how you store and use your data.
Here's a class you could use to load, store and delete data into the NSDocumentDirectory:
DKStoreManager.h
#interface DKStoreManager : NSObject
+ (NSArray *)loadBusinessCardContentForKey:(NSString *)key;
+ (void)storeBusinessCardContent:(NSArray *)content forKey:(NSString *)key;
+ (void)removeBusinessCardForKey:(NSString *)key;
#end
DKStoreManager.m
#interface DKStoreManager () {
NSString * _rootPath;
}
#end
#implementation DKStoreManager
- (id)init {
self = [super init];
if (self) {
// get the root path of the Document Directory
// NSCacheDirectory is also good to use
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
_rootPath = [paths objectAtIndex:0];
}
return self;
}
+ (DKStoreManager *)sharedInstance {
static DKStoreManager *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[DKStoreManager alloc] init];
});
return sharedInstance;
}
#pragma mark - storing management methods
// store a data into a file in a specific sub directory
- (id)storeObject:(id)object inFile:(NSString *)filename inDirectory:(NSString *)directory {
NSString *fullPath = [_rootPath stringByAppendingPathComponent:directory];
if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath])
[[NSFileManager defaultManager] createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:nil error:nil];
fullPath = [fullPath stringByAppendingPathComponent:filename];
BOOL result = [NSKeyedArchiver archiveRootObject:object toFile:fullPath];
if (result)
NSLog(#"Successfully saved %#/%#", directory, filename);
else
NSLog(#"ERROR: can't save %#/%#", directory, filename);
return (result ? object : nil);
}
// remove a file in a specific sub directory
- (void)removeFile:(NSString *)filename inDirectory:(NSString *)directory {
NSString *fullPath = [_rootPath stringByAppendingPathComponent:directory];
if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath])
return ;
fullPath = [fullPath stringByAppendingPathComponent:filename];
NSError *error = [NSError new];
if ([[NSFileManager defaultManager] removeItemAtPath:fullPath error:&error])
NSLog(#"Successfully removed %#/%#", directory, filename);
else
NSLog(#"ERROR: can't remove %#/%# : %#", directory, filename, [error localizedDescription]);
}
// get the data stored into a file
- (id)loadObjectInFile:(NSString *)filename inDirectory:(NSString *)directory {
NSString *fullPath = [_rootPath stringByAppendingPathComponent:directory];
if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath])
return nil;
fullPath = [fullPath stringByAppendingPathComponent:filename];
return [NSKeyedUnarchiver unarchiveObjectWithFile:fullPath];
}
#pragma mark - business cards methods
+ (NSArray *)loadBusinessCardContentForKey:(NSString *)key {
DKStoreManager *storeManager = [DKStoreManager sharedInstance];
return [storeManager loadObjectInFile:key inDirectory:#"business_cards"];
}
+ (void)storeBusinessCardContent:(NSArray *)content forKey:(NSString *)key {
DKStoreManager *storeManager = [DKStoreManager sharedInstance];
[storeManager storeObject:content inFile:key inDirectory:#"business_cards"];
}
+ (void)removeBusinessCardForKey:(NSString *)key {
DKStoreManager *storeManager = [DKStoreManager sharedInstance];
[storeManager removeFile:key inDirectory:#"business_cards"];
}
#end
I don't really understand what you want to do but a good way to use this class could be:
NSArray *contents = [DKStoreManager loadBusinessCardContentForKey:aBusinessCard.name];
[DKStoreManager storeBusinessCardContent:aContent forKey:aBusinessCard.name];
[DKStoreManager removeBusinessCardForKey:aBusinessCard.name];
By the way you can store any data/object you want with this class: NSArray, NSDictionnary,... and even your own class the only thing you need to do is to implement the NSCoding protocol
I want to check one file in Document folder.I want if this file not exist in document folder copy it from main bundle to document folder. I write this code and this file to be copy but my problem here.....!!!! my file is .sqlite file (Database file) and when copy to document folder hasn't data in self!!!! why??? while the this file when is in main bundle has data in self.
this is my code but I don't know why not work!!!!
#define DataName #"mydatabase.sqlite"
- (void)viewDidLoad
{
[self CopyDatabase];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (NSString*)DatabasePath
{
NSArray *Paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *DocumentDir = [Paths objectAtIndex:0];
//NSLog(#"%#",DocumentDir);
return [DocumentDir stringByAppendingPathComponent:DataName];
}
- (void)CopyDatabase
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:[self DatabasePath]];
NSString *FileDB = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:DataName];
if (success)
{
NSLog(#"File Exist");
return;
}
else
{
[fileManager copyItemAtPath:FileDB toPath:[self DatabasePath] error:nil];
}
}
I don't think your documents folder is updating because an older version of that db exists. You can purge your documents directory with the following method, and add it to the top of your viewDidLoad:
- (void)viewDidLoad
{
[self purgeDocumentsDirectory];
[self CopyDatabase];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)purgeDocumentsDirectory
{
NSLog(#"Purging Documents Directory...");
NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *error = nil;
for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error]) {
[[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
}
}
This is my solution
-(void) copytoDocument {
NSString *openFile ;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pgnPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.text", #"100_Greatest_games"]];
if ([fileManager fileExistsAtPath:pgnPath] == NO)
{
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:#"100_Greatest_games" ofType:#"text"];
[fileManager copyItemAtPath:resourcePath toPath:pgnPath error:&error];
if (error) {
NSLog(#"Error on copying file: %#\nfrom path: %#\ntoPath: %#", error, resourcePath, pgnPath);
}
}
}
I have created some directories in NSDocumentDirectory as
if (![tbxCreateFolder.text isEqualToString:#""]) {
NSArray *arrPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryStr = [arrPaths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectoryStr stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#",tbxCreateFolder.text]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
NSError* error;
if([[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]){
NSLog(#"success");
//Perfrom DB Insertation
}
else
{
NSLog(#"[%#] ERROR: attempting to write create MyFolder directory", [self class]);
NSAssert( FALSE, #"Failed to create directory maybe out of disk space?");
}
}
}
Now i want to get the list of directories that i have created in document folder but response is
NSArray *arrPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePathString = ([arrPaths count] > 0) ? [arrPaths objectAtIndex:0] : nil;
NSLog(#"dirContents %#",basePathString);
Response is:
/Users/amir/Library/Application Support/iPhone Simulator/6.1/Applications/7003E8D5-CCBB-4E54-896B-F4BD2F4D2CB1/Documents
Here is the code:
NSString *documentDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// create directory named "test"
[[NSFileManager defaultManager] createDirectoryAtPath:[documentDirPath stringByAppendingPathComponent:#"test"] withIntermediateDirectories:YES attributes:nil error:nil];
// retrieved all directories
NSLog(#"%#", [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirPath error:nil]);
NSArray *paths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirPath error:nil];
BOOL isDir = NO;
for (NSString *path in paths) {
if ([fileManager fileExistsAtPath:path isDirectory:&isDir] && isDir) {
// path is directory
}
}
You could always enumerate the contents of the top level directory using -fileExistsAtPath:isDirectory: like this:
NSFileManager *sharedFileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *files = [sharedFileManager enumeratorAtPath:yourPath];
for (NSString *path in files) {
BOOL isDirectory = NO;
[sharedFileManager fileExistsAtPath:path isDirectory:&isDirectory];
if (isDirectory) {
// you found a directory, so do what you will with it
}
}
You can do this with few simple lines of code
NSString *documentDirectoryPath = // Initialize with Documents path
BOOL isDir = NO;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *files = [fileManager contentsOfDirectoryAtPath:documentDirectoryPath error:NULL];
NSMutableArray *directoriesPaths = [NSMutableArray array];
for (NSString *filePath in files) {
if ([fileManager fileExistsAtPath:filePath isDirectory:&isDir] && isDir) {
[directoriesPaths addObject:filePath];
}
}
NSLog(#"directories %#", directoriesPaths);
try this,
NSArray *arrPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *strFilePath = [[arrPath objectAtIndex:0]
[[NSFileManager defaultManager] createDirectoryAtPath:[strFilePath stringByAppendingPathComponent:#"Sample"] withIntermediateDirectories:YES attributes:nil error:nil];
I want to retrieve in an array of the name of the files in Resources folder that have the .html extension. I have done this:
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Resources"];
NSError *error = nil;
NSArray *documentArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error];
for (int i=0; i < [documentArray count] - 1; i++) {
NSLog(#"value %#", [documentArray objectAtIndex:i]);
}
But the for loop displays continously null. Anyone knows how can I get this task right? thank you
Don't use NSHomeDirectory. Use [[NSBundle mainBundle] resourcePath] to get path to app's resources.
Edited: here's your example code.
NSString *resPath = [[NSBundle mainBundle] resourcePath];
NSError *error = nil;
NSArray *filenames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:resPath error:&error];
if (!error)
{
for (NSString * filename in filenames)
{
NSString *extension = [filename pathExtension];
if ([extension isEqualToString:#"html"])
{
NSLog(#"%#", filename);
}
}
}