I am trying to fetch Images which i am storing in directory which i have shown in below code . I have tried a lot in StachOverFlow And Chats but not able to achieve the task . Actually i want to generate array of images from the array of filePath which are storing the path of images . Which i will show in UICollectionView . Please check my code and tell me what all can be done to achieve the needed . Thanks in advance
I have array of filepath already generated , i just want to fetch images from them and show it in grid view
-(void)plistRender{
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"PhotoBucket.plist"];
//pngDATA.....
NSString *totalName = [NSString stringWithFormat:#"EGK_%# ", [NSDate date]];
PhotodocumentsPath = [paths objectAtIndex:0];
PhotofilePath = [PhotodocumentsPath stringByAppendingPathComponent:totalName]; //Add the file name
NSData *pngData = UIImagePNGRepresentation(printingImage);
//Write image to the file directory .............
[pngData writeToFile:[self documentsPathForFileName:PhotofilePath] atomically:YES];
[photos_URL addObject:PhotofilePath];
[photos addObject:totalName];
[grid_copy addObject:[NSNumber numberWithInteger:count]];
[grids addObject:whichProduct];
[Totalamount addObject:[NSNumber numberWithInteger:amt]];
NSDictionary *plistDictionary = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: photos,grids,grid_copy,Totalamount,nil] forKeys:[NSArray arrayWithObjects: #"Photo_URL",#"Product",#"Copy",#"Amount", nil]];
NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDictionary format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistData)
{
// write plistData to our Data.plist file
[plistData writeToFile:plistPath atomically:YES];
}
else
{
NSLog(#"Error in saveData: %#", error);
}
NSString *string = [[NSString alloc] initWithData:plistData encoding:NSUTF8StringEncoding];
NSLog(#" plist Data %#", string);
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"PhotoBucket"]){
RecipeCollectionViewController *photoBucket = [segue destinationViewController];
NSLog(#"Prepare Segue%#",photoBucket.photoCollection);
NSLog(#"Number of photos %#",photos_URL);
NSMutableArray *imgQueue = [[NSMutableArray alloc] initWithCapacity:photos_URL.count];
for (NSString* path in photos_URL) {
[imgQueue addObject:[UIImage imageWithContentsOfFile:path]];
}
photoBucket.photoCollection = imgQueue;
}
}
try this
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:#"jpg"] || [[strFilePath pathExtension] isEqualToString:#"png"] || [[strFilePath pathExtension] isEqualToString:#"PNG"])
{
NSString *imagePath = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
}
}
}
Hi you can fetch like this:
NSArray *pathPlist1 =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryStr1 = [pathPlist1 objectAtIndex:0];
NSString *plistLocation1 =
[documentsDirectoryStr1 stringByAppendingPathComponent:#"ImageStorage"];
NSFileManager *filemgr;
NSArray *filelist;
int i;
filemgr =[NSFileManager defaultManager];
filelist = [filemgr contentsOfDirectoryAtPath:plistLocation1 error:NULL];
NSLog(#"filelist =%lu",[filelist count]);
cacheImagesArray=[[NSMutableArray alloc] init];
cacheImagesDataArray=[[NSMutableArray alloc] init];
for (i = 0; i < [filelist count]; i++){
NSLog(#"%#", [filelist objectAtIndex: i]);
NSString *imageName=[NSString stringWithFormat:#"%#",[filelist objectAtIndex: i]];
NSString *path=[NSString stringWithFormat:#"%#/%#",plistLocation1, [filelist objectAtIndex: i]];
NSLog(#"Path is =%#",path);
NSData* data = [NSData dataWithContentsOfFile:path];
[cacheImagesDataArray addObject:data];
[cacheImagesArray addObject:imageName];
}
thanks
Related
I successfully added my dictionary to plist but when i add 2nd time it remove my old dictionary from my plist.
Here is my code :
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"favQuote.plist"];
NSDictionary *plistDict = [[NSDictionary alloc] initWithObjectsAndKeys:self.txtQuote.text,#"quote",self.lblAuthor.text,#"author",nil];
NSError *error = nil;
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListWriteStreamError error:&error];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
NSLog(#"Data saved sucessfully");
}
else
{
NSLog(#"Data not saved");
}
How do I add my new dictionary without losing old data?
You should store your dictionary of array in your document directory something like,
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"favQuote.plist"];
NSFileManager *manager = [NSFileManager defaultManager];
NSMutableArray *arr = [[NSMutableArray alloc]init];
if ( [manager fileExistsAtPath:plistPath]) {
NSData *data = [NSData dataWithContentsOfFile:plistPath];
arr = (NSMutableArray*)[NSKeyedUnarchiver unarchiveObjectWithData:data];
}
NSDictionary *plistDict = [[NSDictionary alloc] initWithObjectsAndKeys:#"test",#"quote",#"test2",#"author",nil];
[arr addObject:plistDict];
NSData *plistData = [NSKeyedArchiver archivedDataWithRootObject:arr];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
NSLog(#"Data saved sucessfully");
}
else
{
NSLog(#"Data not saved");
}
then you can retrieve and use your values like,
NSMutableArray *arr1 = [[NSMutableArray alloc]init];
if ( [manager fileExistsAtPath:plistPath]) {
NSData *data = [NSData dataWithContentsOfFile:plistPath];
arr1 = (NSMutableArray*)[NSKeyedUnarchiver unarchiveObjectWithData:data];
}
if (arr1.count > 0) {
NSDictionary *firstDic = [arr1 objectAtIndex:0];
}
self.toDoItems = [[NSMutableArray alloc] init]; //initialize array
self.dataFileName = #"PropertyList";
self.filePath = [self.dataFileName stringByAppendingString:#".plist"];
self.rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
self.filePath = [self.rootPath stringByAppendingPathComponent:self.filePath];
self.NSSRootNodeName = #"ToDoList"; //name of the root node in the property list
// if (![[NSFileManager defaultManager] fileExistsAtPath: self.filePath]) {
// self.filePath = [[NSBundle mainBundle] pathForResource:self.dataFileName ofType:#"plist"];
// }
NSLog(#"File path: %#", self.filePath);
// Uncomment the following line to preserve selection between presentations.
self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem;
//read xml file and load to array
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:self.filePath];
if (plistXML==nil) {
NSLog(#"Error reading plistXML");
}
NSDictionary *rootDictionary = (NSDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
if (!rootDictionary) {
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
the output is below. I am not sure why I get these errors below:
My PropertyList.plist is sitting in my Documents folder inside my application.
could someone point out what I am doing wrong.
File path: /Users/Computer/Library/Application Support/iPhone Simulator/7.1/Applications/78B5F9BA-8376-4001-ACA0-936D9B4D6342/Documents/PropertyList.plist
Error reading plistXML
Error reading plist: stream had too few bytes, format: 0
FWIW, here is what worked for me:
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath: [self filePathForState]])
{
printf("found state file\n");
NSData *data = [NSData dataWithContentsOfFile:[self filePathForState]];
...
}
else
{
printf("no state file found\n");
}
[fileManager release];
- (NSString *) filePathForState
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *result = [documentsDirectory stringByAppendingPathComponent: #"circles06"];
printf("filePathForState: %s\n", [result UTF8String]);
return result;
}
- (void) saveState
{
NSData *state = [model stateData];
[state writeToFile: [self filePathForState] atomically: NO];
}
I am recently having a memory crash and I am suspecting that I am failing to empty the array, This is my code for the array
- (void)viewDidLoad
{
allImagesArray = [[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *location=#"Bottoms";
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:location];
NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: fPath];
collectionBottoms.delegate =self;
collectionBottoms.dataSource=self;
for(NSString *str in directoryContent){
NSLog(#"i");
NSString *finalFilePath = [fPath stringByAppendingPathComponent:str];
NSData *data = [NSData dataWithContentsOfFile:finalFilePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[allImagesArray addObject:image];
NSLog(#"array:%#",[allImagesArray description]);
}}
}
Ho can I free the memory by releasing the object in the array?
You save the image array in Plist. After save you just re initialize your array it will clear the memory in array. Then are you using ARC or not? Because ARC is more comfortable for this. Then re-initialze or removeAllObject from array in -viewWillDisappear
Hi Just release the memory once object works is over. Here is the code for you.
- (void)viewDidLoad
{
allImagesArray = [[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *location=#"Bottoms";
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:location];
NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: fPath];
collectionBottoms.delegate =self;
collectionBottoms.dataSource=self;
for(NSString *str in directoryContent)
{
NSString *finalFilePath = [fPath stringByAppendingPathComponent:str];
NSData *data = [NSData dataWithContentsOfFile:finalFilePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[allImagesArray addObject:image];
NSLog(#"array:%#",[allImagesArray description]);
image = nil;
}
finalFilePath=nil;
data=nil;
}
paths= nil;
documentsDirectory= nil;
location= nil;
fPath= nil;
directoryContent = nil;
}
If you are using this image array, allImagesArray, when the view is visible then put this code in viewWillAppear or viewDidAppear methods of UIViewController.
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
allImagesArray = [[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *location=#"Bottoms";
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:location];
NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: fPath];
collectionBottoms.delegate =self;
collectionBottoms.dataSource=self;
for(NSString *str in directoryContent){
NSLog(#"i");
NSString *finalFilePath = [fPath stringByAppendingPathComponent:str];
NSData *data = [NSData dataWithContentsOfFile:finalFilePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[allImagesArray addObject:image];
NSLog(#"array:%#",[allImagesArray description]);
}
}
}
And, then release it in viewWillDisappear/viewDidDisappear methods of UIViewController.
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[allImagesArray removeAllObjects];
//[allImagesArray release]; // (Uncomment) Call this only if you are not using ARC.
}
Alternatively, a quick, dirty but safe fix is (without knowing your usage of allImagesArray) -
- (void)viewDidLoad
{
[super viewDidLoad];
// Remove previously added objects.
if (allImagesArray != nil && allImagesArray.count > 0) {
[allImagesArray removeAllObjects];
}
// Allocate memory if not done earlier (i.e. first time).
if (allImagesArray == nil) {
allImagesArray = [[NSMutableArray alloc] init];
}
// Rest of your code as stated in your question
}
I am trying to save an NSMutable Array and NSString into plist and then if it exists initialize the value from plist. However when I re run the app, the values do not get initialize as it is suppose to. So far the following is what I have.
if (self = [super init]) {
NSString *path=[self getFileUrl];
NSFileManager *fm = [[NSFileManager alloc] init];
if ([fm fileExistsAtPath:path]) {
_history = [d objectForKey:#"stringKey"];
class=[d objectForKey: #"ArrayKey"];
}
NSDictionary *d;
However the values are not getting initialized as per the plist. Is it the way I am extracting the values from the dictionary?
here is my function that saving json into plist in nscachesdirectory
-(void)saveproducts{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:#"Products.plist"];
NSDictionary*dict = [NSDictionary dictionary];
NSMutableArray *types = [NSMutableArray array];
NSArray *dictArray = [NSArray array];
NSArray *dictKeys = [NSArray array];
NSArray *productObjects = [NSArray array];
NSArray *productKeys = [NSArray array];
for (int i=0; i<appDelegate.products.count; i++) {
NSMutableArray *tmpProds = [NSMutableArray array];
NSString *t_ID = [[appDelegate.products objectAtIndex:i] valueForKey:#"id"];
NSString *t_image = [[appDelegate.products objectAtIndex:i] valueForKey:#"image"];
NSString *t_name =[[appDelegate.products objectAtIndex:i] valueForKey:#"name"];
NSArray *products = [[appDelegate.products objectAtIndex:i] valueForKey:#"products"];
NSDictionary *productsDict = [NSDictionary dictionary];
for (int j=0; j<products.count; j++) {
NSString *p_id = [[products objectAtIndex:j] valueForKey:#"id"];
NSString *p_name = [[products objectAtIndex:j] valueForKey:#"name"];
NSString *p_name2 = [[products objectAtIndex:j] valueForKey:#"name2"];
NSString *image = [[products objectAtIndex:j] valueForKey:#"image"];
NSString *typeID = [[products objectAtIndex:j] valueForKey:#"type_id"];
NSString *active = [[products objectAtIndex:j] valueForKey:#"active"];
NSString *available = [[products objectAtIndex:j] valueForKey:#"available"];
NSString *desc = [[products objectAtIndex:j] valueForKey:#"description"];
NSString *price = [[products objectAtIndex:j] valueForKey:#"price"];
if ([p_name2 isEqual:[NSNull null]]) {
p_name2 =#"undefined";
}
if ([desc isEqual:[NSNull null]]) {
desc = #"";
}
productObjects = [NSArray arrayWithObjects:p_id,p_name,p_name2,image,typeID,active,available,desc,price, nil];
productKeys = [NSArray arrayWithObjects:#"id",#"name",#"name2",#"image",#"type_id",#"active",#"available",#"desc",#"price", nil];
productsDict = [NSDictionary dictionaryWithObjects:productObjects forKeys:productKeys];
[tmpProds addObject:productsDict];
if (![image isEqualToString:#""]) {
[foodImages addObject:image];
}
}
dictArray = [NSArray arrayWithObjects:t_ID,t_image,t_name,tmpProds, nil];
dictKeys = [NSArray arrayWithObjects:#"id",#"image",#"name",#"products", nil];
dict = [NSDictionary dictionaryWithObjects:dictArray forKeys:dictKeys];
[types addObject:dict];
}
NSDictionary* plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:types, nil] forKeys:[NSArray arrayWithObjects:#"ptype", nil]];
NSString *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:YES forKey:#"cached"];
[defaults synchronize];
}
else
{
NSLog(#"Error log: %#", error);
}
}
and this one reading plist
-(void)loadFromplist{
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:#"Products.plist"];
NSData *plistData = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSDictionary *dict = (NSDictionary*)[NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListMutableContainersAndLeaves format:nil errorDescription:nil];
productsArray = [dict valueForKey:#"ptype"];
[self.tableView reloadData];
}
Is it possible to prevent non-set properties (in plist) from deleting?
My Code:
- (NSString*)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
- (void)store {
if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:textField.text forKey:#"text"];
[dict setValue:textField2.text forKey:#"text2"];
[dict writeToFile:[[self dataFilePath] stringByAppendingPathComponent:fileName] atomically:NO];
}
}
- (void)load {
if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:[[self dataFilePath] stringByAppendingPathComponent:fileName]];
textField.text = [dict objectForKey:#"text"];
textField2.text = [dict objectForKey:#"text2"];
}
}
If I comment the line [dict setValue:textField2.text forKey:#"text2"]; out, the property will be deleted. Is it possible to say overwrite property, but keep existing?
Maik
U can append your string and then store in plist like this:
- (void)store {
if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSString *strText = [dict objectForKey:#"text"];
[dict setValue:[strText stringByAppendingString:textField.text] forKey:#"text"];
NSString *strText2 = [dict objectForKey:#"text2"];
[dict setValue:[strText2 stringByAppendingString:textField2.text] forKey:#"text2"];
[dict writeToFile:[[self dataFilePath] stringByAppendingPathComponent:fileName] atomically:YES];
}
}
This is my Solution:
- (NSString*)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
- (void)storeDictionary:(NSDictionary*)values {
if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
NSMutableDictionary *dict = [self load];
NSArray *allKeys = values.allKeys;
for (int i = 0; i < allKeys.count; i++) {
[dict setValue:[values objectForKey:[allKeys objectAtIndex:i]] forKey:[allKeys objectAtIndex:i]];
}
[dict writeToFile:[[self dataFilePath] stringByAppendingPathComponent:fileName] atomically:NO];
}
}
- (NSMutableDictionary*)load {
NSMutableDictionary *dict;
if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
dict = [[NSMutableDictionary alloc] initWithContentsOfFile:[[self dataFilePath] stringByAppendingPathComponent:fileName]];
}
return dict;
}
Maik