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.
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.
I have two view controllers(viewController and popUpViewController). When i open app, viewController will load. It has buttons. When i click on button, image will be opened in popUpViewController. Then i click close button on popUpViewController,i am dismissing popUpViewController. My scenario is, when i click button in viewController i have to take opened time and i click close button on popUpViewController, i have to take end time.Both should be stored in an array. But array is showing as nil. I am using the following code.
viewController.m
viewDidLoad:
fileOpenedValues = #[#"",#"" ,#""];
fileOpenedKeys = #[#"File Name",#"STime",#"ETime"];
fileOpened = [[NSMutableDictionary alloc] initWithObjects:fileOpenedValues forKeys:fileOpenedKeys];
[fileOpenedArr addObject:fileOpened];
-(void) storeArrayFromPopUp :(NSString *)fname second:(NSString *)mname third:(NSString *)lname
{
fileOpenedValues = #[fname ,mname ,lname];
fileOpenedKeys = #[#"File Name",#"STime",#"ETime"];
fileOpened = [[NSMutableDictionary alloc] initWithObjects:fileOpenedValues forKeys:fileOpenedKeys];
[fileOpenedArr addObject:fileOpened];
}
popUpViewController.m
[baseObj storeArrayFromPopUp :openedFileName second:fileOpenStime third:fileOpenEtime];
After calling storeArrayFromPopUp. fileOpenedArr is showing as nil.
Please advice.
#implementation ViewController {
NSString *strStartTime;
NSString *strEndTime;
NSMutableArray *arrTime;
}
- (void)viewDidLoad {
[super viewDidLoad];
arrTime = [[NSMutableArray alloc]init];
strStartTime = #"";
strEndTime = #"";
}
-(void)viewWillAppear:(BOOL)animated {
//check start has value means popupview controller was open.
//viewWillAppear always call when you close the popup.
if (strStartTime.length > 0) {
strEndTime = [self getCurrentTime];
NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:strStartTime,#"StartTime",strEndTime,#"EndTime", nil];
[arrTime addObject:dic]; //you can have all the start and endtime details in the arrTime array.
strStartTime = #"";
strEndTime = #"";
}
}
-(IBAction)btnShowPopupClicked:(id)sender {
//Set the start time when popup is going to open.
strStartTime = [self getCurrentTime];
[self performSegueWithIdentifier:#"imagePopup" sender:nil];
}
-(NSString *)getCurrentTime {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *currentTime = [dateFormatter stringFromDate:[NSDate date]];
return currentTime;
}
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");
}
I am working on IOS application.Integrated Dropbox successfully and saving data as record in datastores in DropBox as well.It was fine till here.But I am unable to get data after deleting application and reinstalling it.But in one scenario I am getting data i.e,"I inserted a record in any one of the tables in datastores,after inserting that when I am trying to get data Its coming successfully".But I need to get for the first time as the app installs.If any one worked on it please help me.Thanks in advance.
-(void)dropBoxScuccessLogin:(NSString *)successString
{
if ([successString isEqualToString:#"scuccess"])
{
//appdelegate.window.rootViewController = appdelegate.splitview;
NSArray *array1=[appdelegate.datastoreManager listDatastores:nil];
NSLog(#"array is %#",array1);
if (self.account)
{
NSDate *mydate=[NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM-DD-yyyy hh:mm:ss a"];
NSString *stringFromDate = [formatter stringFromDate:mydate];
DBTable *customerTbl = [self.store getTable:#"DataSyncedOndate"];
DBRecord *task = [customerTbl insert:#{ #"SyncedDate": stringFromDate} ];
__weak DropBoxViewController *slf = self;
[self.store addObserver:self block:^ {
if (slf.store.status & (DBDatastoreIncoming | DBDatastoreOutgoing))
{
[self syncTasks];
}
}];
[self.store sync:nil];
}
}
else
{
NSLog(#"Dropbox Login faild");
}
}
- (void)syncTasks
{
NSLog(#"Self Account is in syncTasks is %#",self.account);
if (self.account)
{
NSDictionary *changed = [self.store sync:nil];
NSLog(#" Data is Synced");
// [self getDataSync];
dispatch_async(dispatch_get_main_queue(), ^{
[self retriveDataFromDB];
});
// [self performSelector:#selector(getDataSync) withObject:nil afterDelay:2.0];
}
else
{
// [alertView show];
}
}
in retriveDataFromDB method
-(void)retriveDataFromDB
{
NSLog(#"retrive from DB method called");
///////////Admin details///////////
NSMutableArray *tasks = [NSMutableArray arrayWithArray:[[self.store getTable:#"PriceList"] query:nil error:nil]];
NSLog(#"tasks count is %d",[tasks count]);
for (int k=0; k<[tasks count]; k++)
{
DBRecord *recordObj=[tasks objectAtIndex:k];
NSString *Tier1_Id =recordObj[#"Tier1"];
NSString *Tier2_Id =recordObj[#"Tier2"];
NSString *Tier3_Id =recordObj[#"Tier3"];
NSString *Code_Id =recordObj[#"Code"];
NSString *CRV_Id =recordObj[#"CRV"];
NSString *insertAdminString = [NSString stringWithFormat:#"INSERT INTO admin_Tbl(Code,Tier1,Tier2,Tier3,CRV) VALUES(\"%#\",\"%#\",\"%#\",\"%#\",\"%#\")",Code_Id,Tier1_Id,Tier2_Id,Tier3_Id,CRV_Id];
BOOL isDataadded = [appdelegate executeInsertQuery:insertAdminString];
if (isDataadded == YES)
{
NSLog(#"admin table insertrd successfully");
}
else
{
NSLog(#"admin table not insertrd successfully");
}
}
}
In Log I am getting tasks count is "0".
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSDateFormatter * formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm"];
NSString *latitude = [NSString stringWithFormat:#"%f", newLocation.coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", newLocation.coordinate.longitude];
NSString *stringFromDate = [formatter stringFromDate:newLocation.timestamp];
resultsLabel.text = [NSString stringWithFormat:#"(%#) %# Location %.06f %.06f %#", ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) ? #"bg" : #"fg", resultsLabel.tag == 0 ? #"gps:" : #"sig" , newLocation.coordinate.latitude, newLocation.coordinate.longitude, [formatter stringFromDate:newLocation.timestamp]];
NSLog(#"%#", resultsLabel.text);
LocationTestAppDelegate * appDelegate = (LocationTestAppDelegate *)[UIApplication sharedApplication].delegate;
[appDelegate log:resultsLabel.text];
}
But i get this as output.
(null)
on :
NSLog(#"%#", resultsLabel.text);
Does anyone know what im doing wrong?
- (id) initWithLabel:(UILabel*)label
{
resultsLabel = label;
return [super init];
}
And in my delegate i set the resultLabel here:
- (void) log:(NSString*)msg
{
NSDateFormatter * formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
NSString * logMessage = [NSString stringWithFormat:#"%# %#", [formatter stringFromDate:[NSDate date]], msg];
NSString * fileName = [self locationPath];
FILE * f = fopen([fileName UTF8String], "at");
fprintf(f, "%s\n", [logMessage UTF8String]);
fclose (f);}
EDIT
I deleted the GPS functionality.
Does anyone know how a proper NSLog would be in the newlocation. longitude latitude timestamp?
EDIT 2
I set the resultlabel here:
#interface LocationDelegate : NSObject <CLLocationManagerDelegate>
{
UILabel * resultsLabel;
NSString * _phonenumber;
}
- (id) initWithLabel:(UILabel*)label;
//-(id)initWithDictionary:(NSDictionary *)dict;
//-(id)initWithName:(NSString *)aName;
//-(NSDictionary *)toDictionary;
#property (nonatomic , retain) NSString *phonenumber;
Your init code is strange. This is more usual:
- (id) initWithLabel:(UILabel*)label
{
if (self = [super init]) {
resultsLabel = label; // Or maybe _resultsLabel, depending on your code
}
return self;
}
And then access what I presume is an instance variable through self.resultsLabel.
Presumably your problem is that resultsLabel is already nil when you try to set it's text. Sending a message to nil does nothing, not even give an error.