patternMinor
Age verification in Objective-C
Viewed 0 times
ageobjectiveverification
Problem
I'm creating some age-verification functionality for an iOS app. The user is presented with a
UIDatePicker object, and the latest selectable date should be today minus 18 years. How vulnerable to inaccuracy is my code? How could it be leaner?-(void)validateAge {
NSDateComponents *today = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger day = [today day];
NSInteger month = [today month];
NSInteger year = [today year];
int correctYear = year - 18;
NSDateComponents *correctAge = [[NSDateComponents alloc] init];
[correctAge setDay:day];
[correctAge setMonth:month];
[correctAge setYear:correctYear];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
UIDatePicker *agePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 240, 320, 200)];
[agePicker setDatePickerMode:UIDatePickerModeDate];
[agePicker setMaximumDate:[calendar dateFromComponents:correctAge]];
[self.view addSubview:agePicker];
return;
}Solution
Check this method. Pass value as minus 18 (-18)
-(NSDate *)offsetYear:(int)numOfYears date:(NSDate*)date {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setYear:numOfYears];
return [gregorian dateByAddingComponents:offsetComponents
toDate:date options:0];
}Code Snippets
-(NSDate *)offsetYear:(int)numOfYears date:(NSDate*)date {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setYear:numOfYears];
return [gregorian dateByAddingComponents:offsetComponents
toDate:date options:0];
}Context
StackExchange Code Review Q#16145, answer score: 2
Revisions (0)
No revisions yet.