UIDatePicker and UITextView - ios

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];
}

Related

Parse filename for label Xcode

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];

Find out next most close date from NSDate array of times

How can I find out the next prayer from the array of times, I have total 6 Prayers at different times and i want to compare each one with current time and have to find out which one is most near as a next prayer, Date format also creating problems because it give always in UTC format and I have to use local time zone, I am using the following code:
NSMutableArray *arrayTimeIntervals = [[NSMutableArray alloc]init];
NSMutableArray *intervals = [[NSMutableArray alloc]init];
NSMutableArray *arrayPrayers = [[NSMutableArray alloc]init];
[arrayPrayers addObject:#{#"prayer":#"prayer 1",#"time":#"1:12 am"}];
[arrayPrayers addObject:#{#"prayer":#"prayer 2",#"time":#"5:45 am"}];
[arrayPrayers addObject:#{#"prayer":#"prayer 3",#"time":#"12:03 pm"}];
[arrayPrayers addObject:#{#"prayer":#"prayer 4",#"time":#"3:30 pm"}];
[arrayPrayers addObject:#{#"prayer":#"prayer 4",#"time":#"6:20 pm"}];
[arrayPrayers addObject:#{#"prayer":#"prayer 6",#"time":#"7:50 pm"}];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm a"];
NSMutableArray *dates = [NSMutableArray arrayWithCapacity:arrayPrayers.count];
for (NSDictionary *timeDict in arrayPrayers)
{
NSString *timeString = [timeDict objectForKey:#"time"];
NSString *name = [timeDict objectForKey:#"prayer"];
NSDate *date = [dateFormatter dateFromString:timeString];
[dates addObject:#{#"prayer":name,#"time":timeString, #"date":date}];
}
for (int i =0 ; i<arrayPrayers.count; i++) {
NSDictionary *timeDict = arrayPrayers[i];
NSString *timeString = [timeDict objectForKey:#"time"];
//NSString *name = [timeDict objectForKey:#"prayer"];
NSDate *date = [dateFormatter dateFromString:timeString];
NSComparisonResult result = [[NSDate date] compare:date];
if(result==NSOrderedAscending){
NSLog(#"next prayer");
}else if(result==NSOrderedDescending){
NSLog(#"last prayer");
}else{
NSLog(#"current prayer");
}
if ([date earlierDate:[NSDate date]]) {
NSTimeInterval interval = [date timeIntervalSinceNow];
NSDictionary *tempDict = #{#"Prayer":timeDict,
#"Time":timeString,
#"Index":[NSString stringWithFormat:#"%d",i],
#"Interval":[NSString stringWithFormat:#"%f",interval]};
[arrayTimeIntervals addObject:tempDict];
[intervals addObject:[NSString stringWithFormat:#"%f",interval]];
}
}
NSNumber * min = [intervals valueForKeyPath:#"#min.doubleValue"];
NSUInteger index = 0;
for(int i =0 ; i<intervals.count; i++)
{
NSDictionary* dict = arrayTimeIntervals[i];
if([[dict objectForKey:#"Interval"] intValue] == [min intValue]) {
index = i;
NSLog(#"next prayer is!!!:%ld",index);
break;
}
}
NSDictionary *dict = [arrayTimeIntervals objectAtIndex:index];
NSLog(#"next prayer object is:%#",dict);

Combining 2 NSDateFormatters into one

Currently I have two NSDateFormatters in my app and I want to somehow "combine" them so I only have, since they're parsing the same date.
I have a NSObject called UpcomingReleases, thats where all my JSON info gets stored.
UpcomingRelease.h
- (NSString *) formattedDate;
UpcomingRelease.m
- (NSString *) formattedDate {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *readableDate = [dateFormatter dateFromString:self.release_date];
[dateFormatter setDateFormat:#"MMMM dd"];
return [dateFormatter stringFromDate:readableDate];
}
My UICollectionViewController (UpcomingReleasesViewController.m)
if([upcomingReleaseDictionary objectForKey:#"release_date"] != NULL)
{
NSString *readableDate = [upcomingReleaseDictionary objectForKey:#"release_date"];
UpcomingRelease *upcoming = [[UpcomingRelease alloc] init];
upcoming.release_date = readableDate;
cell.release_date.text = [NSString stringWithFormat:#"%#", upcoming.formattedDate];
}
My detailedViewController (ReleaseViewController.m)
(_singleRelease is a NSDictionary)
- (void)viewDidLoad
{
[super viewDidLoad];
if([_singleRelease objectForKey:#"release_date"] != NULL)
{
NSString *readableDate = [_singleRelease objectForKey:#"release_date"];
UpcomingRelease *singleRelease = [[UpcomingRelease alloc] init];
singleRelease.release_date = readableDate;
self.release_date.text = [NSString stringWithFormat:#"%#", singleRelease.formattedDate];
}
}
This was working fine, until I added a share on twitter action and I had to add another NSDateFormatter so it could show the readable date inside the tweet (I would get an error saying "No visible interface for ReleaseViewController declares the selected 'formattedDate'" otherwise).
- (NSString *) formattedDate:(NSString *)jsonDateString {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *readableDate = [dateFormatter dateFromString:jsonDateString];
[dateFormatter setDateFormat:#"MMMM dd"];
return [dateFormatter stringFromDate:readableDate];
}
#pragma mark - Share on twitter
- (IBAction)shareOnTwitter:(id)sender {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
NSString *formattedDate = [self formattedDate:[_singleRelease objectForKey:#"release_date"]];
[tweetSheet setInitialText:[NSString stringWithFormat:#"%#", formattedDate]];
[self presentViewController:tweetSheet animated:YES completion:nil];
}
}
How can I combine both these NSDateFormatters into one? They're both parsing the same string in the same way (also if there's a better way to show the formattedDate string than the one I'm currently doing would be great).
This is how my JSON shows the date string:
release_date: "2013-11-16T00:00:00.000Z"
Thanks.
As #Hot Licks says:
Make the date formatter a class method:
+ (NSString *) formattedDate:(NSString *)jsonDateString {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *readableDate = [dateFormatter dateFromString:jsonDateString];
[dateFormatter setDateFormat:#"MMMM dd"];
return [dateFormatter stringFromDate:readableDate];
}
Put it in a utility class and use it in both cases. In the first case just pass in self.release_date.

NSNumber becomes nil when used in NSDictionary initialization

I have the following code block:
NSNumber* dayNsNumber = [[NSNumber alloc] initWithInt:dayNumber+1];
NSLog(#"dayNsNumber: %d", [dayNsNumber intValue]);
if(boolVar){
UIAlertView* success = [[UIAlertView alloc] initWithTitle:#"Title" message:[NSString stringWithFormat:#"Day %d!", dayNumber+1] delegate:self cancelButtonTitle:nil otherButtonTitles:#"Star", nil];
[success show];
NSLog(#"dayNsNumber: %d", [dayNsNumber intValue]);
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
dayNsNumber, "Day Number",
[self getCurrentLocalDate], #"Date",
[self getCurrentLocalTime], #"Time",
nil];
}
What happens is that when I run the code, it hangs upon initialization of the params NSDictionary and says that dayNsNumber is nil.
Xcode displays a Thread 1: EXC_BAD_ACCESS (code=1).
How do I solve thie issue? I would like to add the dayNsNumber to my params dictionary.
Additionally, here are getCurrentLocalDate and getCurrentLocalTime:
-(NSString*)getCurrentLocalDate;{
NSString *formatString = [NSDateFormatter dateFormatFromTemplate:#"dd-MM-yyyy" options:0 locale:[NSLocale currentLocale]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:formatString];
NSString *todayString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(#"todayString: \"%#\"", todayString);
return todayString;
}
-(NSString*)getCurrentLocalTime;{
NSString *formatString = [NSDateFormatter dateFormatFromTemplate:#"HH:mm:ss zzz" options:0 locale:[NSLocale currentLocale]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:formatString];
NSString *timeString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(#"timeString: \"%#\"", timeString);
return timeString;
}
The problem is with the key: "Day Number" should be #"Day Number".
Also note that you can now use the new syntax for your numbers, arrays, and dictionaries. For example, this
NSNumber* dayNsNumber = [[NSNumber alloc] initWithInt:dayNumber+1];
can be rewritten like this:
NSNumber* dayNsNumber = #(dayNumber+1);
and the dictionary initialization can be done like this:
NSDictionary *params = #{
#"Day Number" : dayNsNumber
, #"Date" : [self getCurrentLocalDate]
, #"Time" : [self getCurrentLocalTime]
};
try this
NSDictionary *params = [[NSDictionary alloc]init];
[params setValue:[daysNumber stringValue] forKey:#"Day Number"];

Crash in NSDateformatter setDateFormat method

-(NSString*) convertToDateString:(NSString*)str{
static NSDateFormatter *InDateFormatter = nil;
static NSDateFormatter *OutDateFormatter = nil;
NSString *outDate = nil;
if([str isKindOfClass:[NSString class]] && [str length] > 0){
NSString *dateStr = [[NSString alloc] initWithString:str];
if (InDateFormatter == nil) {
InDateFormatter = [[NSDateFormatter alloc] init];
InDateFormatter.dateFormat = #"yyyy-MM-dd";
}
if (OutDateFormatter == nil) {
OutDateFormatter = [[NSDateFormatter alloc] init];
OutDateFormatter.dateFormat = #"MM/dd/yy";
}
NSRange rangeOfDash = [dateStr rangeOfString:#"T"];
dateStr = (rangeOfDash.location != NSNotFound) ? [dateStr substringToIndex:rangeOfDash.location] : dateStr;
if([dateStr isKindOfClass:[NSString class]] && [dateStr length] == 10){
NSDate* date = [InDateFormatter dateFromString:dateStr];
if (date != nil) {
outDate = [OutDateFormatter stringFromDate:date];
}
}
}
return outDate;
}
Crash occurred in the line "InDateFormatter.dateFormat = #"yyyy-MM-dd";
There will be multiple instances of class that gets created in parallel and invokes the above method. Crash is rarely reproducible.
Am I not using the date formatter correctly? Thanks in advance
For a thread-safe lazy initialization, you can use the GCD dispatch_once()
function:
static NSDateFormatter *inDateFormatter;
static NSDateFormatter *outDateFormatter;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
inDateFormatter = [[NSDateFormatter alloc] init];
inDateFormatter.dateFormat = #"yyyy-MM-dd";
outDateFormatter = [[NSDateFormatter alloc] init];
outDateFormatter.dateFormat = #"MM/dd/yy";
});

Resources