Hi in my application i have a registration form in my application and I'm validating all fields like email and phone number. But i want to validate this DOB in format like DD/MM/YY. I'm using else if condition checking for my validation i want do same for DOB
I'm validation with else if condition like this.
- (IBAction)send:(id)sender {
if ([self phonevalidate:[ph text]]!= 1){
UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:#"Message" message:#"pls enter valid 10 digit number" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert1 show];
[alert1 release];
}
else if ([self validateEmail:[emd text]]!= 1){
UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:#"Message" message:#"pls enter valid email id" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert1 show];
[alert1 release];
}
My validation function for phone.
-(BOOL)phonevalidate:(NSString *)phh
{
NSString *phoneRegex = #"[0-9]{10}";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneRegex];
return [phoneTest evaluateWithObject:phh];
}
I'm not using the UIDate Picker i have UITextfield for the DOB i want validate with UITextfield itself.Like the above i want to validate the DOB please tell me how to validate the DOB and check int else if condition.
Thanks.
EDITED:
Assume that b'date is
NSString *dateOfBirth = #"22/03/14";
And this is method for check b'date is valid or not ?
-(BOOL) isValidateDOB:(NSString *) dateOfBirth
{
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateStyle:NSDateFormatterShortStyle];
[format setDateFormat:#"dd/MM/yy"];
NSDate *validateDOB = [format dateFromString:dateOfBirth];
if (validateDOB != nil)
return YES;
else
return NO;
}
In above method [format setDateStyle:NSDateFormatterShortStyle]; and setDateFormat is very important in your case:
Now you can check it as like,
if([self isValidateDOB:dateOfBirth])
{
// b"date is valid;
}
else
{
// b"date is not valid;
}
You can use UIDatePicker for this :
Initialize like this :
UIDatePicker datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.date = [NSDate date];
Then, set the inputView of your textField (the one that takes DOB as input) :
yourDOBtextField.inputView = datePicker;
Then, implement textFieldDidEndEditing: delegate method for UITextField:
- (void) textFieldDidEndEditing:(UITextField *)textField {
if (textField == yourDOBtextField) {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd/MM/yy";
yourDOBtextField.text = [dateFormatter stringFromDate:datePicker.date];
[dateFormatter release];
}
}
That's it.
Let's try below codes:
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"DD/MM/YY"];
NSDate *date = [dateFormatter dateFromString:#"12/12/2014"];
If (date)
{
NSLog(#"Valid date");
}
Related
I am trying to do a massive load of events on a ios calendar either local or in gmail (the calendar chooses the user as I describe in the following answer) using objective-c.
Adding an event with the functions I've put below works fine for me, but when I have to do a massive load of eg 527 events (since I'm trying to add a student's school calendar) it does not work correctly.
When doing the bulk load I inserted well about 100 events or so and then it starts to crash and crash the app.
The errors that it gives me are the following:
2016-11-17 17:23:35.966 [230:11481] Calendar was not set: 1 Error
Domain=EKErrorDomain Code=1 "No calendar selected."
UserInfo={NSLocalizedDescription=No calendar selected.}
2016-11-17 17:23:49.545 [230:12644] Connectioninterrupted!
2016-11-17 17:23:49.568[230:12587] Error getting changed object IDs
since timestamp 501092601.149441 from daemon: Error
Domain=NSMachErrorDomain Code=4097 "unknown error code"
My question is this: Is there any error in my massive loading approach or in the functions I have done? or else Is there any other better way to do a massive load of events?
Function that inserts the list of events:
- (int) addCalendarEvents: (EKCalendar *) cal {
int num = 0;
for (int i=0; i < [calendario.eventos count]; i++) {
NSDictionary * nextDict = [calendario.eventos objectAtIndex:i];
Evento_DTO * evento_dto = [[Evento_DTO alloc] initWithEventos:nextDict];
BOOL res = [self addEventCalendar: evento_dto calendar: cal];
if(res){
num++;
}
}
return num;
}
And the function that adds the event to the calendar is as follows:
-(BOOL)addEventCalendar: (Evento_DTO *) evento calendar: (EKCalendar *) cal{
__block BOOL res = NO;
if (!SYSTEM_VERSION_LESS_THAN(#"6.0")) {
// iOS 6 and later
EKEventStore *eventStore = [[EKEventStore alloc] init];
//We get the dates of the event
Fecha_DTO *fechaStart = [[Fecha_DTO alloc] initWithFecha:(NSDictionary *)evento.dtStart];
Fecha_DTO *fechaEnd = [[Fecha_DTO alloc] initWithFecha:(NSDictionary *)evento.dtEnd];
// Format the dates to type NSDate
// Start Date
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyyMMdd'T'HHmmss"];
if (fechaStart.tzid == nil) {
[df setTimeZone: [NSTimeZone systemTimeZone]];
}else{
[df setTimeZone:[NSTimeZone timeZoneWithName:fechaStart.tzid]];
}
NSDate* parsedDateS = [df dateFromString: fechaStart.fecha];
// End Date
NSDateFormatter* df2 = [[NSDateFormatter alloc] init];
[df2 setDateFormat:#"yyyyMMdd'T'HHmmss"];
if (fechaEnd.tzid == nil) {
[df2 setTimeZone: [NSTimeZone systemTimeZone]];
}else{
[df2 setTimeZone:[NSTimeZone timeZoneWithName:fechaEnd.tzid]];
}
NSDate* parsedDateE = [df2 dateFromString: fechaEnd.fecha];
//rRules
NSString *rfc2445String = evento.rRule; // Usando la libreria EKRecurrenceRule+RRULE.m
EKRecurrenceRule *recurrenceRule;
if (![rfc2445String isEqualToString:#""]) {
recurrenceRule = [[EKRecurrenceRule alloc] initWithString:rfc2445String andTimezone:fechaStart.tzid];
// NSLog(#"RRule: %#", recurrenceRule);
}
if(parsedDateS!=nil){
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted) {
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = evento.summary;
event.notes = evento.description;
event.startDate = parsedDateS;
event.endDate = parsedDateE;
event.location = evento.location;
if (![rfc2445String isEqualToString:#""])
event.recurrenceRules = [NSArray arrayWithObject:recurrenceRule];
event.calendar = [eventStore calendarWithIdentifier: cal.calendarIdentifier];
//[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err = nil;
BOOL success = [eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
if(!success){
if (err) {
NSLog(#"Calendar was not set: %li %#", (long)err.code, err.description);
}
}else{
//NSLog(#"Added Event");
res = YES;
}
} else {
// code here for when the user does NOT allow your app to access the calendar
alerta = [[UIAlertView alloc]initWithTitle:AMLocalizedString(#"Error", #"")
message:AMLocalizedString(#"errorPermisosCal", #"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alerta show];
}
}];
}else{
NSLog(#"The start date is null");
}
df = nil;
df2 = nil;
}else{
alerta = [[UIAlertView alloc]initWithTitle:AMLocalizedString(#"Error", #"")
message:AMLocalizedString(#"VersionEvento", #"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alerta show];
}
return res;
}
Finally I have been able to perform the massive bulk of events without failures, I have modified the methods being as follows:
- (void) addCalendarEvents: (EKCalendar *) cal store: (EKEventStore *) eventStore {
if (!SYSTEM_VERSION_LESS_THAN(#"6.0")) {
// iOS 6 and later
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted) {
//se aƱade cada uno de los eventos
for (int i=0; i < [calendario.eventos count]; i++) {
#autoreleasepool {
NSDictionary * nextDict = [calendario.eventos objectAtIndex:i];
Evento_DTO * evento_dto = [[Evento_DTO alloc] initWithEventos:nextDict];
[self addEventCalendar: evento_dto calendar: cal.calendarIdentifier store: eventStore];
}
}
} else {
// code here for when the user does NOT allow your app to access the calendar
alerta = [[UIAlertView alloc]initWithTitle:AMLocalizedString(#"Error", #"")
message:AMLocalizedString(#"errorPermisosCal", #"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alerta show];
}
}];
}else{
alerta = [[UIAlertView alloc]initWithTitle:AMLocalizedString(#"Error", #"")
message:AMLocalizedString(#"Event version", #"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alerta show];
}
}
And the function that adds the event to the calendar is as follows:
-(void)addEventCalendar: (Evento_DTO *) evento calendar: (NSString *) cal store: (EKEventStore *) eventStore{
//Obtenemos las fechas del evento
Fecha_DTO *fechaStart = [[Fecha_DTO alloc] initWithFecha:(NSDictionary *)evento.dtStart];
Fecha_DTO *fechaEnd = [[Fecha_DTO alloc] initWithFecha:(NSDictionary *)evento.dtEnd];
// Format the dates to type NSDate
// Start Date
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyyMMdd'T'HHmmss"];
if (fechaStart.tzid == nil) {
[df setTimeZone: [NSTimeZone systemTimeZone]];
}else{
[df setTimeZone:[NSTimeZone timeZoneWithName:fechaStart.tzid]];
}
NSDate* parsedDateS = [df dateFromString: fechaStart.fecha];
// End Date
NSDateFormatter* df2 = [[NSDateFormatter alloc] init];
[df2 setDateFormat:#"yyyyMMdd'T'HHmmss"];
if (fechaEnd.tzid == nil) {
[df2 setTimeZone: [NSTimeZone systemTimeZone]];
}else{
[df2 setTimeZone:[NSTimeZone timeZoneWithName:fechaEnd.tzid]];
}
NSDate* parsedDateE = [df2 dateFromString: fechaEnd.fecha];
//rRules
NSString *rfc2445String = evento.rRule;
EKRecurrenceRule *recurrenceRule;
if (![rfc2445String isEqualToString:#""]) {
recurrenceRule = [[EKRecurrenceRule alloc] initWithString:rfc2445String andTimezone:fechaStart.tzid];
//NSLog(#"RRule: %#", recurrenceRule);
}
if(parsedDateS!=nil){
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = evento.summary;
event.notes = evento.description;
event.location = evento.location;
event.startDate = parsedDateS;
event.endDate = parsedDateE;
if (![rfc2445String isEqualToString:#""])
event.recurrenceRules = [NSArray arrayWithObject:recurrenceRule];
event.calendar = [eventStore calendarWithIdentifier: cal];
NSError *err = nil;
BOOL success = [eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
if(!success){
if (err) {
NSLog(#"Calendar was not set: %li %#", (long)err.code, err.description);
}
}else{
NSLog(#"Added Event");
}
}else{
NSLog(#"The start date is null");
}
df = nil;
df2 = nil;
}
I hope it helps somebody.
When I test my game the score of my game ends in a time of 3.49 seconds, but in gamecenter the score that shows up in the leaderboards is 1:01:52.76. I think the problem is that i get a yellow flag that says incompatible integer to integer conversion assigning to int_64 (aka long long) from NSString. Here is the part of the code that shows the error.
- (IBAction)buttonPressed:(id)sender {
[self startTimer];
count--;
countLabel.text = [NSString stringWithFormat:#"Score\n%i", count];
// 2
if (count == 0) {
[self.stopWatchTimer invalidate];
timeLabel.hidden = YES;
// Create date from the elapsed time
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:self.startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
// Create a date formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"'Your time: 'ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
// Format the elapsed time and set it to the label
NSString *timeString = [dateFormatter stringFromDate:timerDate];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Time is up!"
message: timeString
delegate:self
cancelButtonTitle:#"Play Again"
otherButtonTitles:#"Level Select",nil];
[alert show];
if (count == 0) {
GKScore *scoreReporter = [[GKScore alloc] initWithLeaderboardIdentifier:#"tap_novice"];
scoreReporter.value = timeString;
scoreReporter.context = 0;
NSArray *scores = #[scoreReporter];
[GKScore reportScores:#[scoreReporter] withCompletionHandler:^(NSError *error) {
if (error == nil) {
NSLog(#"Score reported successfully!");
} else {
NSLog(#"Unable to report score!");
}
}];
}
}
}
#end
Instead of the current line you have:
scoreReporter.value = timeString;
You should use:
int64_t timeAsInt = [timeString longLongValue];
scoreReporter.value = timeAsInt;
See the following link
I am working with the UIdatepicker. I am fetching the time from the datepicker and showing the date on the label. Once i select the date it is shown on the label and datepicker is hidden away. Now i want that when i call the picker it should show me the selection bar of the datepicker on the date of the label which i selected previously selected on the datepicker.Code i am using is shown below:-
-(void)datepickershown:(UILabel *)time animated:(BOOL)animated
{
UIActionSheet *actionsheet = [[UIActionSheet alloc] initWithTitle:#"Select the Time" delegate:self cancelButtonTitle:nil destructiveButtonTitle:#"DONE" otherButtonTitles:Nil, nil];
pickdate = [[UIDatePicker alloc] initWithFrame:[actionsheet bounds]];
pickdate.hidden = NO;
//pickdate.date = [NSDate date];
pickdate.datePickerMode = UIDatePickerModeTime;
[pickdate addTarget:self action:#selector(changeDateInLabel:) forControlEvents:UIControlEventValueChanged];
[actionsheet addSubview:pickdate];
[actionsheet showInView:self.view];
[actionsheet setBounds:CGRectMake(0,0,320, 500)];
CGRect pickerRect = pickdate.bounds;
pickerRect.origin.y = -90;
pickdate.bounds = pickerRect;
}
- (IBAction)changeDateInLabel:(id)sender
{
NSLog(#"I Am Changing the values");
df = [[NSDateFormatter alloc] init];
df.timeStyle = NSDateFormatterShortStyle;
}
As you want the datepicker to show the date you have already set on the label.
For this you need to use following method.
- (void)setDate:(NSDate *)date animated:(BOOL)animated
Pass the date whatever you have selected and is shown in the label.
try this
[self.datePicker setDatePickerMode:UIDatePickerModeDate];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MM-yyyy"];
if([dateFormat dateFromString:yourDateLabel.text])
{
NSDate *date = [dateFormat dateFromString:yourDateLabel.text];
[self.datePicker setDate:date];
}
hope this will work
I am working with the UIdatepicker. I am fetching the time from the datepicker and showing the date on the label. Once i select the date it is shown on the label and datepicker is hidden away. Now i want that when i call the picker it should show me the selection bar of the datepicker on the date of the label which i selected previously selected on the datepicker.Code i am using is shown below:-
-(void)datepickershown:(UILabel *)time animated:(BOOL)animated
{
UIActionSheet *actionsheet = [[UIActionSheet alloc] initWithTitle:#"Select the Time" delegate:self cancelButtonTitle:nil destructiveButtonTitle:#"DONE" otherButtonTitles:Nil, nil];
pickdate = [[UIDatePicker alloc] initWithFrame:[actionsheet bounds]];
pickdate.hidden = NO;
//pickdate.date = [NSDate date];
pickdate.datePickerMode = UIDatePickerModeTime;
[pickdate addTarget:self action:#selector(changeDateInLabel:) forControlEvents:UIControlEventValueChanged];
[actionsheet addSubview:pickdate];
[actionsheet showInView:self.view];
[actionsheet setBounds:CGRectMake(0,0,320, 500)];
CGRect pickerRect = pickdate.bounds;
pickerRect.origin.y = -90;
pickdate.bounds = pickerRect;
}
- (IBAction)changeDateInLabel:(id)sender
{
NSLog(#"I Am Changing the values");
df = [[NSDateFormatter alloc] init];
df.timeStyle = NSDateFormatterShortStyle;
}
Image below can describe you more
use setDate:animated of UIDatePicker...
- (void)setDate:(NSDate *)date animated:(BOOL)animated
to convert your label.text to NSDate:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];
[dateFormatter setDateFormat:#"hh:mm"]; // depends on 12(hh) or 24(HH)
NSDate *yourDate = [dateFormatter dateFromString:label.text];
I need to be able to show if the switch is on or off in a alert along with other details, all of the details display just fine but when I try to add the notificationStatus string it gives me an error. "Use of undeclared identifier 'notificationStatus'"
-(void) procrastinationNotificationSwitchOnOrOff {
if (_procrastinationNotificationSwitch.on) {
_notificationOnOffLabel.text = #"Procrastination Notification On";
NSString *notificationStatus = #"NOTIFICATION ON";
NSLog(notificationStatus);
}
else {
_notificationOnOffLabel.text = #"Procrastination Notification Off";
NSString *notificationStatus = #"NOTIFICATION OFF";
NSLog(notificationStatus);
}
}
-(void) presentMessage:(NSString *)message {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Class Stuff" message:message delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
-(void) notificationStatus:(NSString *)stat {
NSString *status = [NSString stringWithFormat:#"%#", stat];
}
-(IBAction)returnKeyButton:(id)sender {
[sender resignFirstResponder];
NSString *classNameString = self.className.text;
NSLog(classNameString);
NSString *assignmentTitleString = self.assignmentTitle.text;
NSLog(assignmentTitleString);
NSString *assignmentDescriptionString = self.assignmentDescription.text;
NSLog(assignmentDescriptionString);
NSString *totalStrings = [NSString stringWithFormat:#"%# %# %# %#", classNameString, assignmentTitleString, assignmentDescriptionString, notificationStatus];
NSLog(totalStrings);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
dateFormatter.timeStyle = NSDateFormatterShortStyle;
dateFormatter.dateStyle = NSDateFormatterShortStyle;
NSString *dateTimeString = [dateFormatter stringFromDate: dateTimePicker.date];
NSLog(#"Alarm Set Button Tapped : %#", dateTimeString );
[self presentMessage:totalStrings];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[_procrastinationNotificationSwitch addTarget:self action:#selector(procrastinationNotificationSwitchOnOrOff) forControlEvents:UIControlEventValueChanged];
}
You have a local variable notificationStatus in your method procrastinationNotificationSwitchOnOrOff. You also have notificationStatus. You don't have a property or instance variable notificationStatus.
Add a property notificationStatus. Get rid of the method notificationStatus. Always read and write notificationStatus using self.notificationStatus. Problem solved.
I think you're confusing things by having the method
-(void) notificationStatus:(NSString *)stat {
NSString *status = [NSString stringWithFormat:#"%#", stat];
}
Would be better off making it a local variable and if you want manipulate it, use getters and setters.