The code below returns weather data. All works fine except for the current weather description. For example, if todaysimage file name is partlycloudyv3.png. The description shows as partlycloudy in my app. How can I make it appear as partly cloudy?
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSArray *theView = [[NSBundle mainBundle] loadNibNamed:#"HipSkin01" owner:self options:nil];
UIView *nv = [theView objectAtIndex:0];
NSString *filePathDocArray = [DOCUMENTS stringByAppendingPathComponent:#"r.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:filePathDocArray]) {
NSLog(#"The file exists");
dataz = [[NSMutableDictionary alloc] initWithContentsOfFile:filePathDocArray];
NSLog(#"The file exists %#",dataz);
NSLog(#"The array: %i",(int) [dataz count]);
}
NSString *todaysimage = [dataz valueForKey:#"icon"];
[self.weatherIcon setImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#v3.png", todaysimage]]];
NSArray *arr1 = [dataz objectForKey:#"display_location"];
NSString *plasez = [arr1 valueForKey:#"full"];
//NSString *plasez = [arr1 valueForKey:#"city"];
[self.plase setText:plasez];
//DataFormater
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM dd, YYYY"];
[formatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
[self.dataLable setText:dateToday];
[self.nameWeather setText:todaysimage];
//temp
NSString *tempzC = [dataz valueForKey:#"feelslike_c"];
NSString *tempzF = [dataz valueForKey:#"feelslike_f"];
NSString *terC = [NSString stringWithFormat:#"%#°C",tempzC];
NSString *terF = [NSString stringWithFormat:#"%#°F",tempzF];
[self.temprC setText:terC];
[self.temprF setText:terF];
[self addSubview:nv];
}
return self;
}
I added these lines and the parsing issue was solved. I was referencing the incorrect item in the weather API.
NSString *todaysimage2 = [dataz valueForKey:#"weather"];
[self.weatherIcons setImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#v3.png", todaysimage]]];
[self.weatherData setText:dateToday];
[self.weatherText setText:todaysimage2];
Related
This question already has answers here:
Formatting date and time in UITableView cells
(3 answers)
Closed 7 years ago.
in my project i am working on comment section i take a UITextfield to enter a comment and a UITableView to show the comments when Post comment button pressed.
All i want to show the Current date and time along with the commented text in the same cell like as in faceBook which shows date and time with comment.
please suggest me some code what i have to apply to show it
currently i am using the following code to put text input to UITableView
here i created custom label in table view cell
detaillabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 0, 55, 45) ];
detaillabel.text = #"";
[cell.contentView addSubview:detaillabel];
Post Comment codes:
-(IBAction)postcomment:(id)sender;
{
NSError *error;
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd.MM.YY HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
detaillabel.text=dateString;
NSFileManager *filemanager = [NSFileManager defaultManager];
NSMutableDictionary *messageDictionary = [NSMutableDictionary new];
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *messageString = [array objectAtIndex:0];
NSString *datallist =[messageString stringByAppendingPathComponent:#"message.plist"];
if(commentsarray == Nil)
{
commentsarray = [[NSMutableArray alloc]init];
}
NSInteger contactid = 0;
if(datallist)
{
BOOL isFileExist = [filemanager fileExistsAtPath:datallist];
if(isFileExist)
{
commentsarray = [NSMutableArray arrayWithContentsOfFile:datallist];
}
}
if(commentsarray.count >0)
{
NSDictionary *dic = [commentsarray objectAtIndex:(commentsarray.count - 1)];
NSInteger val = [[dic objectForKey:#"id"] integerValue];
contactid = val+1;
}
else{
contactid = 1;
}
[messageDictionary setObject:[NSNumber numberWithInteger:contactid] forKey:#"id"];
[messageDictionary setObject:messageText.text forKey:#"id"];
[commentsarray addObject:messageDictionary];
NSData *data = [NSPropertyListSerialization dataFromPropertyList:commentsarray format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(data)
{
[data writeToFile:datallist atomically:YES];
[commentstable reloadData];
//[messagingtable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow: messagearray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
[commentstable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:commentsarray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
else
{
NSLog(#"Error in save data: %#",error);
}
}
You can use NSDateComponent and NSDate. See Apple's Date and Time Programming Guide
I've been racking my brain over this for the past week now and can't quite figure out how to go about this.
I currently have an app that takes in survey data, saves it as a csv file in the form of surveydata-mm-dd-yyyy. This usually goes out to events that last multiple days so a normal event weekend would be
surveydata-09-13-2014
surveydata-09-14-2014
surveydata-09-15-2014
Now I want the person who is at these events to be able to simply click a button that will prepend an e-mail with all those files which are being stored in the apps documents folder.
I have it all pretty much setup and functioning minus being able to tell the app to look for those files with those names and to include them in the e-mail.
Here is the code I have
- (IBAction)emailButton:(id)sender {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM-dd-yyyy"];
NSString *dateString = [dateFormat stringFromDate:[NSDate date]];
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:[NSString stringWithFormat:#"_SurveyData_%#.csv",dateString]];
/* if(![[NSFileManager defaultManager] fileExistsAtPath:path]) {*/
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"CSV File"];
[mailer setToRecipients:toRecipents];
[mailer addAttachmentData:[NSData dataWithContentsOfFile:#"_SurveyData_%#.csv"]
mimeType:#"text/csv"
fileName:#"FileName"];
[self presentModalViewController:mailer animated:YES];
//}
}
If somebody could please help me out as I feel like I'm so close I'm just waiting for it to all click and make sense.
Please let me know if I'm missing something or my code is too vague.
This is the code that i'm using to write the data to the CSV for better understanding of how it's all going down.
-(void)writeSurveyDataToCSV:(NSString *)text {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM-dd-yyyy"];
NSString *dateString = [dateFormat stringFromDate:[NSDate date]];
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:[NSString stringWithFormat:#"_SurveyData_%#.csv",dateString]];
if(![[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSString *header = #" gender,age,zip code,duration(sec), own a bike?,response1,response2,response3,response4,response5,response6, response7, response8, response9\n";
[header writeToFile:path atomically:YES
encoding:NSUTF8StringEncoding error:nil];
}
text = [text stringByAppendingString:#"\n"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[text dataUsingEncoding:NSUTF8StringEncoding]];
}
EDIT: Thanks to Danh's guidance here's my solution
- (IBAction)emailButton:(id)sender {
NSArray *toRecipents = [NSArray arrayWithObject:#"reflex#ilovetheory.com"];
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"CSV File"];
[mailer setToRecipients:toRecipents];
NSArray *filenames = [self filesNamesStartingAt:[NSDate date] count:165];
[self attachFilesNamed:filenames toMailer:mailer];
[self presentModalViewController:mailer animated:YES];
}
// answer count strings, named for days starting at date and the count-1 following days
- (NSArray *)filesNamesStartingAt:(NSDate *)date count:(NSInteger)count {
NSMutableArray *result = [NSMutableArray array];
static NSDateFormatter *dateFormat;
if (!dateFormat) {
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM-dd-yyyy"];
}
for (int i=0; i<count; ++i) {
NSString *dateString = [dateFormat stringFromDate:date];
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:[NSString stringWithFormat:#"_SurveyData_%#.csv",dateString]];
[result addObject:path];
date = [self addDayToDate:date];
}
for (int i=0; i<count; ++i) {
NSString *dateString = [dateFormat stringFromDate:date];
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:[NSString stringWithFormat:#"_SurveyData_%#.csv",dateString]];
[result addObject:path];
date = [self subDayToDate:date];
}
return result;
}
// answer a new date, advanced one day from the passed date
- (NSDate *)addDayToDate:(NSDate *)date {
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:1];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
return [gregorian dateByAddingComponents:components toDate:date options:0];
}
- (NSDate *)subDayToDate:(NSDate *)date {
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:-1];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
return [gregorian dateByAddingComponents:components toDate:date options:0];
}
- (void)attachFilesNamed:(NSArray *)paths toMailer:(MFMailComposeViewController *)mailer {
for (NSString *path in paths) {
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSData *data = [NSData dataWithContentsOfFile:path];
[mailer addAttachmentData:data mimeType:#"text/csv" fileName:path];
} else {
NSLog(#"warning, no file at path %#", path);
}
}
}
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
}
It does look like you're very close. Maybe decomposing the problem a little more is what's needed:
Start with a method that will create the file names for several days starting at a given day...
// answer count strings, named for days starting at date and the count-1 following days
- (NSArray *)filesNamesStartingAt:(NSDate *)date count:(NSInteger)count {
NSMutableArray *result = [NSMutableArray array];
static NSDateFormatter *dateFormat;
if (!dateFormat) {
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM-dd-yyyy"];
}
for (int i=0; i<count; ++i) {
NSString *dateString = [dateFormat stringFromDate:date];
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:[NSString stringWithFormat:#"_SurveyData_%#.csv",dateString]];
[result addObject:path];
date = [self addDayToDate:date];
}
return result;
}
// answer a new date, advanced one day from the passed date
- (NSDate *)addDayToDate:(NSDate *)date {
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:1];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
return [gregorian dateByAddingComponents:components toDate:date options:0];
}
Now, add a method that will attach a set of named files to a mail controller:
- (void)attachFilesNamed:(NSArray *)paths toMailer:(MFMailComposeViewController *)mailer {
for (NSString *path in paths) {
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSData *data = [NSData dataWithContentsOfFile:path];
[mailer addAttachmentData:data mimeType:#"text/csv" fileName:path];
} else {
NSLog(#"warning, no file at path %#", path);
}
}
}
The rest practically writes itself (I hope)...
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:#"CSV File"];
[mailer setToRecipients:toRecipents];
NSArray *filenames = [self fileNamesStartingAt:[NSDate date] count:3];
[self attachFilesNamed:filenames toMailer:mailer];
Note that, as written, this will use today and the next two days for filenames. If this isn't your requirement, you can tweak the addDay method to create a subtract days method, then work with those in tandem.
You're creating a filepath, but in the [mailer addAttachmentData] call, you're not passing in that path as I assume you intended--instead it's just getting the string that you used to build the path, so your NSData is going to be nil because it's not a complete path to anything on disk. Try changing that line to [mailer addAttachmentData:[NSData dataWithContentsOfFile:path]]
ok I'm learning to use xCode(5) and I want to use a csv file (screenshot) to read data to store into 7 separate arrays. However, I'm having problems separating the 7 values. I know I'm supposed to use "componentsSeparatedByString" in my case, by ","...but Idk where to place it. Any advice would be appreciated!
csv screenshot: http://i61.tinypic.com/qz5ie8.png
*7th value is " ", used for other purposes.
{
[super viewDidLoad];
// 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;
NSError *error;
NSString *allEntries = [NSString stringWithContentsOfFile:#"fighterbase.csv" encoding:NSUTF8StringEncoding error:&error];
NSArray *rows = [allEntries componentsSeparatedByString:#"\n"];
_names = [[NSMutableArray alloc] init];
_origins = [[NSMutableArray alloc] init];
_ages = [[NSMutableArray alloc] init];
_heights = [[NSMutableArray alloc] init];
_weights = [[NSMutableArray alloc] init];
_games = [[NSMutableArray alloc] init];
_images = [[NSMutableArray alloc] init];
for(int i = 0; i < [rows count]; i++)
{
[_names addObject:[rows objectAtIndex:0]];
[_origins addObject:[rows objectAtIndex:1]];
[_ages addObject:[rows objectAtIndex:2]];
[_heights addObject:[rows objectAtIndex:3]];
[_weights addObject:[rows objectAtIndex:4]];
[_games addObject:[rows objectAtIndex:5]];
[_images addObject:[rows objectAtIndex:6]];
}
NSLog(#"Name: %# Origin: %# Age:%#", [_names objectAtIndex:0], [_origins objectAtIndex:0], [_ages objectAtIndex:0]);
}
This should do the trick:
for(int i = 0; i < [rows count]; i++)
{
NSArray *arrayLine = [[row objectAtIndex:i] componentsSeparatedByString#","];
[_names addObject:[arrayLine objectAtIndex:0]];
[_origins addObject:[arrayLine objectAtIndex:1]];
[_ages addObject:[arrayLine objectAtIndex:2]];
[_heights addObject:[arrayLine objectAtIndex:3]];
[_weights addObject:[arrayLine objectAtIndex:4]];
[_games addObject:[arrayLine objectAtIndex:5]];
[_images addObject:[arrayLine objectAtIndex:6]];
}
But in your image, I didn't see there was a 7th value, which may be crash it if it doesn't exist. Well, you said "*7th value is " "", so you may want to manage it.
I am honestly not able to figure out when to release these objects. Could anyone guide me in the right direction?
+ (DrawData*) load {
DrawData *newDrawData = [[DrawData alloc] init];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fm = [NSFileManager defaultManager];
BOOL keepLoading = YES;
int curIndex = 0;
while ( keepLoading ) {
BoardData *tmpBoard = [[BoardData alloc] init];
NSString *imageFilename = [[NSString alloc] initWithFormat:#"iCanvas_image_%d.png", curIndex];
NSString *metadataFilename = [[NSString alloc] initWithFormat:#"iCanvas_metadata_%d.txt", curIndex];
NSString *layersFilename = [[NSString alloc] initWithFormat:#"iCanvas_layers_%d.dat", curIndex];
imageFilename = [documentsDirectory stringByAppendingPathComponent:imageFilename];
metadataFilename = [documentsDirectory stringByAppendingPathComponent:metadataFilename];
if ( [fm fileExistsAtPath:imageFilename] && [fm fileExistsAtPath:metadataFilename] ) {
NSString *metadataFile = [[NSString alloc] initWithContentsOfFile:metadataFilename];
NSArray *metadata = [metadataFile componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
tmpBoard.drawImageTypeOverlay = [[metadata objectAtIndex:0] intValue];
tmpBoard.brushSize = [[metadata objectAtIndex:1] floatValue];
tmpBoard.brushColorRed = [[metadata objectAtIndex:2] floatValue];
tmpBoard.brushColorGreen = [[metadata objectAtIndex:3] floatValue];
tmpBoard.brushColorBlue = [[metadata objectAtIndex:4] floatValue];
tmpBoard.brushColorAlpha = [[metadata objectAtIndex:5] floatValue];
tmpBoard.isErasing = [[metadata objectAtIndex:6] intValue];
tmpBoard.eraseSize = [[metadata objectAtIndex:7] floatValue];
tmpBoard.isSelected = [[metadata objectAtIndex:8] intValue];
tmpBoard.layers = [NSMutableArray arrayWithContentsOfFile:layersFilename];
[newDrawData addBoard:tmpBoard];
}
else {
keepLoading = NO;
}
[tmpBoard release];
}
[pool release];
return newDrawData;
}
You should get in the habit of either:
1) Adding to autorelease pool
NSString *imageFilename = [[[NSString alloc] initWithFormat:#"iCanvas_image_%d.png", curIndex] autorelease];
OR
2) sending a release message (when done working with it)
[imageFilename release];
to variables you declare with this pattern:
NSString *imageFilename = [[NSString alloc] initWithFormat:#"iCanvas_image_%d.png", curIndex];
Which is basically
[[blah alloc] init];
Read more: http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/MemoryMgmt/
I'm not sure if you want to return autoreleased newDrawData - check your ownership logic.
imageFilename and metadataFilename are overwritten directly after +alloc/-initWithFormat:
metadataFile is allocated but not released.
Points 2 and 3 are repeated in a while loop which may increase the number of actual leaks.
I want to show a text in UITextView depend on the date, some thing like "in This Day App", I have this code in action
-(void)changingText:(id)sender {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
label.text = [NSString stringWithFormat:#"%#", [df stringFromDate:datePicker.date]];
NSDictionary *pageData = [[DataSource sharedDataSource] dataForPage:pageIndex];
NSString *dateText = [pageData objectForKey:#"pageName"];
NSString *dateInfo = [df stringFromDate:datePicker.date];
if ([dateText isEqualToString: dateInfo]) {
myText.text = [pageData objectForKey:#"pageText"];
}
[df release];
}
My qustion is how to update UITextView With the data from NSDictionery ForKey#"pageText" , because it shows just the first object.
here is the Object that i want to triger when the date been selected.
- (id)init {
self = [super init];
if (self != nil)
{
dataPages = [[NSArray alloc] initWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
#"Oct 3, 2009", #"pageName",
#"First Object", #"pageText",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
#"Oct 10, 2009", #"pageName",
#"second Object", #"pageText",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
#"Oct 27, 2009", #"pageName",
#"Third Object", #"pageText",
nil],
nil];
}
return self;
}
I'm not sure if I understand your question, but I think you need to make the object from your dictionary into an NSString like this:
-(void)changingText:(id)sender{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
NSDictionary *pageData = [[DataSource sharedDataSource] dataForPage:pageIndex];
NSString *dateText = (NSString *)[pageData objectForKey:#"pageName"];
NSString *dateInfo = [df stringFromDate:datePicker.date];
label.text = [NSString stringWithFormat:#"%#", [df stringFromDate:dateInfo]];
if ([dateText isEqualToString: dateInfo]) {
myText.text = dateText;
}
[df release];
}