How to get the pdf file lists folder by folder? - iphone

Now i am currently working on pdf reader application, i can read all the pdf files which are present inside the application by using the following code,
NSArray *userDocuments = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSURL *docementsURL = [NSURL fileURLWithPath:[userDocuments lastObject]];
NSArray *documentsURLs = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:docementsURL
includingPropertiesForKeys:nil
options:NSDirectoryEnumerationSkipsHiddenFiles
error:nil];
NSMutableArray *names = [NSMutableArray array];
NSMutableDictionary *urls = [NSMutableDictionary dictionary];
NSArray *bundledResources = [[NSBundle mainBundle] URLsForResourcesWithExtension:#"pdf" subdirectory:nil];
documentsURLs = [documentsURLs arrayByAddingObjectsFromArray:bundledResources];
for (NSURL *docURL in documentsURLs)
{
NSString *title = [[docURL lastPathComponent] stringByDeletingPathExtension];
[names addObject:title];
[urls setObject:docURL forKey:title];
}
documents = [[NSArray alloc] initWithArray:[names sortedArrayUsingSelector:#selector(compare:)]];
urlsByName = [[NSDictionary alloc] initWithDictionary:urls];
But my problem is to read the pdf file folder by folder and store that in to separate arrays,
my folder structure is like the following image,
Any help regarding this will be appreciated..

For this purpose you can create bundles instead of folders
and then get all bundles and files inside them
something like this
NSArray *bundleArr = [[NSBundle mainBundle]pathsForResourcesOfType:#"bundle" inDirectory:nil];
NSLog(#"pdfs in bundle %# is my class is %#",[bundleArr objectAtIndex:0],[[bundleArr objectAtIndex:0]class]);
for (int i=0; i<[bundleArr count]; i++) {
NSString *myBundleStr=[bundleArr objectAtIndex:i];
NSBundle *myBundle = [[NSBundle alloc]initWithPath:[bundleArr objectAtIndex:i]];
NSArray *pdfPaths = [myBundle pathsForResourcesOfType:#"pdf" inDirectory:nil];
NSLog(#"\n\nPDF in bundle is %#",pdfPaths);
}

Related

Save arrays in folders

I want to create different folders for each user's account. There are images of user's that are need to be stored in their folder. How can i achieve that i am getting no idea.Can anyone help me.
Thanks in advance.
Create directory in your app like this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:#"UniqueUserAccount"];
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath])
[[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
Now saving NSMutableArray refer read-and-write-array-dictionary-and-other-collections-to-files link.
folderPath = [folderPath stringByAppendingPathComponent:#"array.out"];
[yourArray writeToFile:folderPath atomically:YES];
Read array like this:
NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:folderPath];
NSLog(#"%#",arrayFromFile);
EDIT : To save image in user account folder from array of images
for(int i = 0;i < [arrImages count];i++)
{
folderPath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d",i]]; //here folder Path with Image file
//Our goal is to create UIImage into NSData if u have image in bundle then take like this:
NSMutableString *imgPath;
imgPath=[[NSMutableString alloc] initWithString: [[NSBundle mainBundle] resourcePath]]; //get bundle path
[imgPath stringByAppendingPathComponent:[arrImages objectAtIndex:i]]; //get image from bundle to write
NSData *imageData = [NSData dataWithContentsOfFile:imgPath]; //create nsdata of image
//if u have UIImage
NSData *imageData = UIImagePNGRepresentation([arrImages objectAtIndex:i]) //image reference here to convert into data
[imageData writeToFile:folderPath atomically:YES]; //write here
}
you can create directory in your app by:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *newFolder = [(NSString*)[paths objectAtIndex:0] stringByAppendingPathComponent:#"uniqueIdentifierForAccount"];
if (![[NSFileManager defaultManager] fileExistsAtPath:newFolder]) {
[[NSFileManager defaultManager] createDirectoryAtPath:newFolder withIntermediateDirectories:YES attributes:nil error:nil];
}
It sounds to me that rather than needing actual folders, you really just need to store an array connected to a name. I would advise using the NSUserDefaults. You can achieve this functionality like this:
//instantiate the NSUserDefaults
NSUserDefaults *storage = [NSUserDefaults standardUserDefaults];
NSArray *userArray;
NSString *username;
//Then to store:
[storage setObject:userArray forKey:username];
//and to recall:
userArray = [storage objectForKey:username];

renaming and saving in NSDocumentsDirectory

Its like this, in my app, I have a UIScrollView on it is a thumbnail view, they are images from my NSCachesDirectory.
I saved them from my picker then named them in my array like: images0.png,images.1.png... etc
So for example I have images in my directory this way : images0.png, images1.png, images2.png, images3.png.
Then I delete images1.png, the remaining images will be like this : images0.png,images2.png, images3.png right?
What I wanted to achieve is get the images in NSDocumentsDirectory then renamed them AGAIN or sort them again like images0.png, images1.png, images2.png...etc again?
is this possible? hope you could help me.
Use this NSFileManger moveItemAtPath: toPath: error: but you should supply the toPath:same_path_but_different_filename. This moves the file to a new path with new file name that you provide. see this
Since it seems you want the whole logic to rename your images file, here is the code you can try provided the files are in the Document directory
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString * oldPath =[[NSString alloc]init];
NSString * newPath =[[NSString alloc]init];
int count=0;
for (int i=0; i<=[[fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil]count]; i++) {
oldPath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"images%d.png",i]];
if ([fileManager fileExistsAtPath:oldPath]) {
newPath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"images%d.png",count]];
[fileManager moveItemAtPath:oldPath toPath:newPath error:nil];
count+=1;
}
}
Apple doesnot allow renameing of file saved. So alternative is to get all contents at document directory like this:
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:yourDocDirPath error:NULL];
Now sort like this:
NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending: YES comparator:^NSComparisonResult(id obj1, id obj2){
return [obj1 compare: obj2 options: NSNumericSearch];
}];
NSArray * sortedDirectoryContent = [directoryContent sortedArrayUsingDescriptors:[NSArray arrayWithObject: descriptor]];
We have sorted array rewrite all files with new name:
for(NSString *fileName in sortedDirectoryContent)
{
NSString *filePath = [yourDocDirPath stringByAppendingPathComponent:fileName];
NSData *fileData = [[NSData alloc]initWithContentsOfFile:filePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
if(fileData)
{
NSString *newFilePath = [yourDocDirPath stringByAppendingPathComponent:#"New Name here"];
[fileData writeToFile:newFilePath atomically:YES];
}
}
else
{
if(fileData)
{
NSString *newFilePath = [yourDocDirPath stringByAppendingPathComponent:#"New Name here"];
[fileData writeToFile:newFilePath atomically:YES];
}
}
}

How to get data from property list into an NSArray programmatically?

I have generated a property list which save some hospital names. Now I want to get the names into an array from that plist. please help me. Thanx in advance.
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"plist"];
contentArray = [NSArray arrayWithContentsOfFile:plistPath];
try this
Try this
NSMutableDictionary* dictionary = [[[NSMutableDictionary alloc] init] autorelease];
NSError *error;
// Look in Documents for an existing plist file
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* metadataPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"Metadata.plist"]];
[metadataPlistPath retain];
// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:metadataPlistPath] ) {
NSString *pathToSettingsInBundle = [[NSBundle mainBundle]
pathForResource:#"Metadata" ofType:#"plist"];
[fileManger copyItemAtPath:pathToSettingsInBundle toPath:metadataPlistPath error:&error];
}
//Now read the plist file from Documents
NSString* myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"Metadata.plist"] ];
dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:myPlistPath];
return dictionary;
}
//fetch the data based on key
- (NSMutableArray*) fetchMetadataArrayForKey:(NSString*)aKey {
NSMutableArray* arrCategories = [[[NSMutableArray alloc] init] autorelease];
NSMutableDictionary* dictionary = [self fetchMetadata];
arrCategories = [dictionary valueForKey:aKey];
return arrCategories;
}

How can I overwrite the contents of a plist file? (iPhone / iPad)

I have a plist file in my main app bundle that I want to update via my app. Here is the code I'm using, the problem is that the plist doesn't seem to be getting updated. Is my code incorrect or is there another issue?
// Data
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setObject:self.someValue forKey:#"Root"];
// Save the logs
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"MyFile" ofType:#"plist"];
[data writeToFile:filepath atomically:YES];
Please can someone help me out?
IOS restricts writing to bundled files. If you want a writable plist, you need to copy it to your app's Documents folder and write to it there.
Here's how I'm doing it in one of my apps
//get file paths
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"document.plist"];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *bundlePlistPath = [bundlePath stringByAppendingPathComponent:#"bundle.plist"];
//if file exists in the documents directory, get it
if([fileManager fileExistsAtPath:documentPlistPath]){
NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
return documentDict;
}
//if file does not exist, create it from existing plist
else {
NSError *error;
BOOL success = [fileManager copyItemAtPath:bundlePlistPath toPath:documentPlistPath error:&error];
if (success) {
NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
return documentDict;
}
return nil;
}
Hope this helps

How can we create our own plist file in a Xcode project?

I want to create "UrlPaths.plist" file in my Application and also a dictionary with 4 or 5 objects. Please help me create a plist file and dictionary. And also read data from that plist file.
I want the plist to add the file to resources folder and i want to add Dictionary at that time also.i dont want pragmatical creation of plist but i want reading the data is pragmatically.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"plist.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableDictionary *data;
if ([fileManager fileExistsAtPath: path]) {
data = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
}
else {
// If the file doesn’t exist, create an empty dictionary
data = [[NSMutableDictionary alloc] init];
}
//To insert the data into the plist
data[#"value"] = #(5);
[data writeToFile: path atomically:YES];
[data release];
//To retrieve the data from the plist
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
int value1;
value1 = [savedStock[#"value"] intValue];
NSLog(#"%i",value1);
[savedStock release];
If you are about to create Plist without programmatically then follow these steps :
1. Right Click on Files in Left Pane and Select 'New File...' option.
2. Choose Resources from OS X tab.
3. An option for Property List is available.
4. Select an give an appropriate name.
This gets added to your project.
We can get simple understanding about plist as below
Now you can read this data as below
NSString *path = [[NSBundle mainBundle] pathForResource:#"Priority" ofType:#"plist"];
NSDictionary *dictPri = [NSDictionary dictionaryWithContentsOfFile:path];//mm
NSMutableArray *arrMarkets=[[NSMutableArray alloc] initWithArray:[dictPri valueForKey:#"List"]];
NSMutableArray *arrForTable=[[NSMutableArray alloc] init];
NSMutableArray *arrForTable1=[[NSMutableArray alloc] init];
for (NSDictionary *dict in arrMarkets)
{
NSString *strS1=nil;
strS1= [NSString stringWithFormat:#"%#",[dict valueForKey:#"Description"] ];
[arrForTable addObject:strS1];
}
NSLog(#"%#----------------- ",[arrForTable description]);
for (NSDictionary *dict in arrMarkets)
{
NSString *strS2=nil;
strS2= [NSString stringWithFormat:#"%#",[dict valueForKey:#"Name"] ];
[arrForTable1 addObject:strS2];
}
NSLog(#"%#----------------- ",[arrForTable1 description]);
create new plist file -
NSArray *Arr = [NSArray arrayWithObjects:obj1,obj2,nil];
NSData *data = [NSPropertyListSerialization dataFromPropertyList:Arr format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
[data writeToFile:PlistDataFilePath atomically:YES];
Read data from this plist file -
NSData *data = [NSData dataWithContentsOfFile:PlistDataFilePath];
NSPropertyListFormat format;
NSArray *array = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:&format errorDescription:nil];
you should read this great tut on plist files - http://www.edumobile.org/iphone/iphone-programming-tutorials/how-to-use-plist-in-iphone/