How to Save Current date and time values in Document Directory? - iphone

As my above screen shot show that I want to show Two values in Each cell of Tableview. I can do it if I have the data which I want to show in these labels of Cell in the same Class,but problem for me is I am try to getting both these labels from other view or other class using (NSDocumentDirectory, NSUserDomainMask, YES) so for I got success to show one value as my screenshot show ,but the other part which consist of current data and time Display is still problem for me.Now here is my code which i try so for.
NSString *fina = [NSString stringWithFormat:#"%#",mySongname];
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath = [docsDir stringByAppendingPathComponent:#"MyRecordings"];
if (![[NSFileManager defaultManager] fileExistsAtPath:soundFilePath])
[[NSFileManager defaultManager] createDirectoryAtPath:soundFilePath withIntermediateDirectories:NO attributes:nil error:nil];
soundFilePath = [soundFilePath stringByAppendingPathComponent:fina];
recordedTmpFile = [NSURL fileURLWithPath:soundFilePath];
recorder = [[ AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:recordSetting error:&error];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];
[recordSetting release];
The above part of Code works fine it display the value in Tableview Cell that my screenshow.Now in same function I am try to getting the data to show it in red part which is my UILabel in Tableview Cell using Below Code.
NSDate* now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd:MMM:YY_hh:mm:ss a"];
NSString *file= [dateFormatter stringFromDate:now];
NSLog(#"myfinaldate:%#",file);
Now i want to save this date value in same directory which i use above and to show it red parts of UITableview .
Now here is my Code where i use this Tableview and getting these document directory value.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentPath = [documentsDirectory stringByAppendingPathComponent:#"MyRecordings"];
directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath:documentPath];
NSLog(#"file found %i",[directoryContent count]);
[directoryContent retain];
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
static NSInteger StateTag = 1;
static NSInteger CapitalTag = 2;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UILabel *capitalLabel = [[UILabel alloc] initWithFrame:CGRectMake(2, 2, 80, 20)];
//capitalLabel.text=#"mydata";
capitalLabel.backgroundColor=[UIColor redColor];
capitalLabel.tag = CapitalTag;
[cell.contentView addSubview:capitalLabel];
[capitalLabel release];
UILabel *stateLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 22, 310, 20)];
stateLabel.tag = StateTag;
[stateLabel setFont:[UIFont systemFontOfSize:14]];
stateLabel.adjustsFontSizeToFitWidth=YES;
[cell.contentView addSubview:stateLabel];
[stateLabel release];
}
UILabel * stateLabel = (UILabel *) [cell.contentView viewWithTag:StateTag];
//UILabel * capitalLabel = (UILabel *) [cell.contentView viewWithTag:CapitalTag];
stateLabel.text = [directoryContent objectAtIndex:indexPath.row];
//capitalLabel.text = [directoryContent1 objectAtIndex:indexPath.row];
return cell;
}
Now I am trying to summarize the problem.
How we can save the date and time value in same directory and then how to show here in Red part of UITableview Cell?
capitalLabel is my Redpart of Cell to show date and time which is problem.
stateLabel all ready show the values. so no problem with this label. Any help will be appreciated.

just do this....
you can set NSCachesDirectory to NSDocumentDirectory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:yourComponent];
// NSLog(#"Path : %#",writableDBPath);
NSMutableDictionary *plistArr = [[NSMutableDictionary alloc] initWithContentsOfFile:writableDBPath];

Related

How to get images form directory in tableView

I am gettting images from documents directory. it's succesfully getiing. but when it's load on table it appear same images on table.
arrayOfImages = [[NSMutableArray alloc]init];
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *stringPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"%#",paths);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"%#",documentsDirectory);
filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files array %#", filePathsArray);
for(i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
NSLog(#"%#",strFilePath);
if ([[strFilePath pathExtension] isEqualToString:#"JPG"] || [[strFilePath pathExtension] isEqualToString:#"png"] || [[strFilePath pathExtension] isEqualToString:#"PNG"])
{
NSString *imagePath = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:strFilePath];
NSLog(#"%#",imagePath);
NSData *data = [NSData dataWithContentsOfFile:imagePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
NSLog(#"%#",image);
[arrayOfImages addObject:image];
NSLog(#"%#",arrayOfImages);
}
}
}
For Table i m calling this code
saveImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10.0, 10.0, 100.0, 80.0)];
[saveImageView setImage:[arrayOfImages objectAtIndex:indexPath.row]];
[cell.contentView addSubview:saveImageView];
Try this in your cellForRowAtIndexPath method.
static NSString *CellIdentifier = #"Cell";
UIImageView *saveImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10.0, 10.0, 100.0, 80.0)];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ; // You cell initialization
saveImageView.tag = 1000;
[cell.contentView addSubview:saveImageView];
}
((UIImageView *)[cell.contentView viewWithTag:1000]).image = [arrayOfImages objectAtIndex:indexPath.row];

How to capture the image automatically in iPhone?

I'm new to iPhone development, I have used UIImagePickerController to capture the image manually, but i want to capture the image automatically, Is it possible to do that.
please help me.
Thanks in advance
Try This. In this I have saved the screen shot in photos album
-(void)screenShotCapture
{
//-- Screen Capture --------------------------------------------------------------------//
UIImage *image = nil;
UIGraphicsBeginImageContext(loginBgImgVw.frame.size);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM-dd-yyyy hh:mm:ss"];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(375, 0, 600, 44)];
[label setText:dateToday];
NSString *fileNameStr = [NSString stringWithFormat:#"%#_Login_%#",providerIdStr,dateToday];
[label setText:fileNameStr];
label.backgroundColor = [UIColor clearColor];
[loginBgImgVw addSubview:label];
[formatter release];
loginBgImgVw.frame = CGRectMake(10, 0, 1006, 669);
[loginBgImgVw.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[label removeFromSuperview];
//=--
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docspath = [paths objectAtIndex:0];
NSLog(#"path=--%#",paths);
NSString *dataPath = [docspath stringByAppendingPathComponent:[NSString stringWithFormat:#"ProviderID_%#",providerIdStr]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *savedImagePath = [dataPath stringByAppendingPathComponent:#"Login_Provider.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.2);
if ([screenCapturNameAry count] != 0)
{
if ([screenCapturNameAry containsObject:#"Login"])
{
[imageData writeToFile:savedImagePath atomically:NO];
}
}
UIImageWriteToSavedPhotosAlbum([self loadImage:#"Login_Provider"],self,#selector(image:didFinishSavingWithError:contextInfo:),NULL);
//--------------------------------------------------------------------------------------//
}
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
if (error == nil)
{
NSLog(#"Login Image saved successfully.");
}
else
{
NSLog(#"Error occurred:%#",[error localizedDescription]);
}
}
You can get the saved image using following method
- (UIImage*)loadImage:(NSString*)imageName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"ProviderID_%#",providerIdStr]];
NSString *fullPath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",imageName]];
return [UIImage imageWithContentsOfFile:fullPath];
}
To take the screenshot you can use the following code.
UIGraphicsBeginImageContext(self.window.bounds.size);
[self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(image);
[data writeToFile:#"screen.png" atomically:YES];
For Ratina display device you have to check:
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)])
UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(self.window.bounds.size);

How To Split NSMutableArry Data into Two parts?

I am Working on Recording Application.in This Application i Save my Recording with my own Text and it also Save the Recording with Current Date and Time.As my below Code show
-(IBAction)RecButtonPress:(id)sender
{
NSLog(#"Song name:%#",mySongname);
NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44000.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];
[recordSetting setValue: [NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recordSetting setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recordSetting setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
NSDate* now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd:MMM:YY_hh:mm:ss a"];
NSString *file= [dateFormatter stringFromDate:now];
NSString *fina=[file stringByAppendingString:mySongname];
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath = [docsDir stringByAppendingPathComponent:#"MyRecordings"];
if (![[NSFileManager defaultManager] fileExistsAtPath:soundFilePath])
[[NSFileManager defaultManager] createDirectoryAtPath:soundFilePath withIntermediateDirectories:NO attributes:nil error:nil];
soundFilePath = [soundFilePath stringByAppendingPathComponent:fina];
recordedTmpFile = [NSURL fileURLWithPath:soundFilePath];
NSLog(#"Uf:%#",recordedTmpFile);
recorder = [[ AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:recordSetting error:&error];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];
[recordSetting release];
[dateFormatter release];
}
Now After Saving Recording When i goes to SaveRecording Class Where actually i Show all these Recording in Tableview.here my Code is
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentPath = [documentsDirectory stringByAppendingPathComponent:#"MyRecordings"];
directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath:documentPath];
NSLog(#"file found %i",[directoryContent count]);
NSLog(#"arraydata: %#", directoryContent );
[directoryContent retain];
[self.tableView reloadData];
}
And After That i Assign "directoryContent" Which is my NSMutablArray To UITableview.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [directoryContent count];
}
//////////////////////////////////////////////////////////////////////////////////////////////
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
static NSInteger StateTag = 1;
static NSInteger CapitalTag = 2;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UILabel *capitalLabel = [[UILabel alloc] initWithFrame:CGRectMake(2, 2, 120, 20)];
//capitalLabel.text=#"mydata";
capitalLabel.backgroundColor=[UIColor redColor];
capitalLabel.tag = CapitalTag;
[capitalLabel setFont:[UIFont systemFontOfSize:9]];
[cell.contentView addSubview:capitalLabel];
[capitalLabel release];
UILabel *stateLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 22, 310, 20)];
stateLabel.tag = StateTag;
[stateLabel setFont:[UIFont systemFontOfSize:14]];
stateLabel.adjustsFontSizeToFitWidth=YES;
[cell.contentView addSubview:stateLabel];
[stateLabel release];
}
UILabel * stateLabel = (UILabel *) [cell.contentView viewWithTag:StateTag];
//UILabel * capitalLabel = (UILabel *) [cell.contentView viewWithTag:CapitalTag];
stateLabel.text = [directoryContent objectAtIndex:indexPath.row];
//capitalLabel.text = [datesaving objectAtIndex:indexPath.row];
return cell;
}
And Finaly my UITableView is Look like this Below ScreenShot
My All this Brief discussion purpose is that as my Screen shot show That UITableview Cell Show my Text and Current date and Time.Now i want to Split this directoryContent Array data into Two prats.The part which Consist of Current date and time i want to Assign it capitalLabel which is redpart of Cell in UITableview And Text to stateLabel Which is Below part of Cell in UITableview.Any help will be Appriated.Thanks in Advance.
First you need to append your string like this
NSString *file3 = [file stringByAppendingString:#"+"];
NSString *fina= [file3 stringByAppendingString:mySongname];
after that you need to seperate it like
NSArray *Array = [str componentsSeparatedByString:#"+"];
NSLog(#"myindex0str:%#",[Array objectAtIndex:0]);
NSLog(#"myindex1str:%#",[Array objectAtIndex:1]);
so you will get the both time and songname individually.
Hi Lena you can try the following things
1) Array of Dictionary
Save your Date and Song name separately in a Dictionary
NSDictionary *myData = [NSDictionary dictionaryWithObjectsAndKeys:myDateObj,#"SongDate",mySongName,#"SongName", nil];
[myMutableArray addObject:myData]//myMutableArray is a NSMutableArray;
Now you can use it as follows
NSDictionary *dict = [directoryContent objectAtIndex:indexPath.row];
stateLabel.text = [dict objectForKey:#"SongName"];
capitalLabel.text = [dict objectForKey:#"SongDate"];
OR
2) Your can do a little trick :)
NSString *fina=[file stringByAppendingFormat:#"+%#",mySongname];
NSArray *Array = [fina componentsSeparatedByString:#"+"];
capitalLabel.text = [Array objectAtIndex:0];
stateLabel.text = [Array objectAtIndex:1];
Here while appending you can use format and add any special character which you can use later to split the string.
Hope this will help you in any ways :)

edit tableView and delete Document file

i've a tabBarController with 4 viewController.
One of this is a TableViewController.
In viewDidLoad of the tableView i inizialize 2 NSMutableArray
list = [[NSMutalbeArray alloc] init];
dates = [[NSMutalbeArray alloc] init];
in viewDidAppear i add objects
NSError *error;
NSError *error1;
fileManager = [NSFileManager defaultManager];
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsPath = [paths objectAtIndex:0];
for (NSString *file in [fileManager contentsOfDirectoryAtPath:docsPath error:&error]) {
fileFrom = [docsPath stringByAppendingPathComponent:file];
NSDictionary* properties = [[NSFileManager defaultManager]
attributesOfItemAtPath:fileFrom
error:&error1];
NSDate* modDate = [properties objectForKey:NSFileModificationDate];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale: [NSLocale currentLocale]];
[dateFormatter setDateStyle:kCFDateFormatterMediumStyle];
[dateFormatter setTimeStyle:kCFDateFormatterNoStyle];
NSString* dateString = [dateFormatter stringFromDate:modDate];
BOOL isDir;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:#"%#/%#", docsPath, file] isDirectory:&isDir];
if (exists && !isDir && ![file hasPrefix:#"."]) {
[list addObject:file];
[dates addObject:dateString];
}
}
[[self tableView] reloadData];
where every file is a filename in my documentDirectory and dateString the creation date.
I can visualize in my tableView the list of file.
If i edit the tableView and try to delete element it works, i can remove the element both from filesystem and on the tableView BUT if i add a new file to my document directory (like the apps do) i receive an EXE_BAD_ADDRESS
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSString *temp = [list objectAtIndex:indexPath.row];
NSString *lastPath = [docsPath stringByAppendingPathComponent:temp];
[fileManager removeItemAtPath:lastPath error:nil];
[self.list removeObjectAtIndex:indexPath.row];
[self.dates removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
[self.tableView reloadData];
}
}
Any advise?

Display image on tableview inside uitbaleviewcell

The following is the code I am using to display image in the table view and its name. It works fine however when we have lot of images inside the folder the app crashes. Any help is greatly appreciated.
NSString *CellIdentifier = #"DocumentList";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *bundleRoot = [paths objectAtIndex:0];
NSString *dataPath = [bundleRoot stringByAppendingPathComponent:[NSString stringWithFormat:#"%d", 1]];
NSString *imagePath = [NSString stringWithFormat:#"%#/%#", dataPath, [itsDocumentNamesArray objectAtIndex:indexPath.row]];
[cell.imageView setImage:[[[UIImage alloc] initWithContentsOfFile:imagePath] autorelease]];
cell.textLabel.text = [itsDocumentNamesArray objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont systemFontOfSize:15.0];
cell.textLabel.textColor = [UIColor grayColor];
UIImageView *temp=[[UIImageView alloc]initWithFrame:CGRectMake(10, 5, 60, 60)]; //40
temp.clipsToBounds=YES;
temp.tag=10;
temp.userInteractionEnabled=YES;
temp.layer.cornerRadius=8.0;
[cell.contentView addSubview:temp];
[temp release];
Have the above part within the cell==nil block and the following piece of code outside...
UIImageView *temp=(UIImageView*)[cell.contentView viewWithTag:10];
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", docDirectory,[tableData objectAtIndex:indexPath.row]];
UIImage *cellImage=[UIImage imageWithContentsOfFile:filePath];
temp.image=cellImage;