Xcode check error to manage event - xcode

I have this method to add an event to iOS calendar:
-(IBAction)addEvent:(id)sender
{
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = nome;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY/MM/dd"];
event.startDate = [formatter dateFromString:startdate];
event.endDate = [formatter dateFromString:enddate];
event.allDay = TRUE;
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
NSLog(#"%#", err);
[formatter release];
}
I would like to test *err to pop up an alert view if the registration has been done successfully.
If it is *err is null: is it correct? If *err=null I have to pop up the alert view.
Can anybody confirm it?
Thanks

Yes this is easily done as EKEventStore's method - (BOOL)saveEvent:(EKEvent *)event span:(EKSpan)span error:(NSError **)error actually returns a YES or NO value depending on the result of the save.
So you could do something like:
if (![eventStore saveEvent:event span:EKSpanThisEvent error:&err])
{
// code for event not saved
} else {
// code for event saved
}

Related

EventKit saveEvent is not working in iOS 7

I have added following code in my application.It is working fine if [comps setYear:1] but if i change year value to 2 or greater than 2 code does not show me any error but also not adding any event in calender. This happens in iOS 7 only. But if I run the same code on iOS 6 , its working correctly & event gets added in calender successfully. Is there any restriction in iOS 7 for adding future events ?
-(void)addEvent{
EKEventStore *es = [[EKEventStore alloc] init];
EKAuthorizationStatus authorizationStatus = [EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent];
BOOL needsToRequestAccessToEventStore = (authorizationStatus == EKAuthorizationStatusNotDetermined);
if (needsToRequestAccessToEventStore) {
[es requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted) {
[self setEventForStore:es];
} else {
}
}];
} else {
BOOL granted = (authorizationStatus == EKAuthorizationStatusAuthorized);
if (granted) {
[self setEventForStore:es];
} else {
}
}
}
-(void)setEventForStore:(EKEventStore*)store{
EKEvent *event = [EKEvent eventWithEventStore:store];
event.title = #"Event 4";
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [NSDateComponents new];
// comps.day =3650;
comps.day=5;
comps.hour=1;
comps.year=2;
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
event.startDate = sevenDays;
NSDate *sevenDays1 = [event.startDate dateByAddingTimeInterval:60*60];;
// duration = 1 h
event.endDate = sevenDays1;
[event setCalendar:[store defaultCalendarForNewEvents]];
NSError *err = nil;
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
}
`
Whenever dealing with dates through components, please set them in the following fashion:
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setDay:05];
[comps setMonth:01];
[comps setYear:2014]; //instead of adding a single digit number like so: 2
//followed by your code...
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
//...
UPDATE 1
You mentioned that your event is not being saved in the calendar when you slightly adjust the integer values in your NSDate's components. One quick way to see whats happening is by NSLogging your date. See what the ouput is before you try to add it to your calendar.
//Right after this below line
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
//Add the code here so we can see what `sevenDays` prints out.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *strDate = [dateFormatter stringFromDate:sevenDays];
NSLog(#"Seven Days date = %#", strDate);

Save value from Action Sheet

I am stuck on something dumb. This app is an OSX core-data app. I'm calling an action sheet to play with dates. The date selected is correctly shown on the screen after the sheet is closed. However, I cannot figure how to save the date.
Any help appreciated. This is the code I'm working with in my AppDelegate.m:
NSDate *theDate = [self.purchaseDatePicker dateValue];
if (theDate)
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSString *formattedDateString;
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
formattedDateString = [formatter stringFromDate:theDate];
[self.purchaseDate setStringValue: formattedDateString];
self.item.purchaseDate = theDate;
[self.item setPurchaseDate:theDate];
[self.item setPurchaseDate:self.item.purchaseDate];
NSLog(#"theDate is %#", theDate); <-- this is fine.
NSLog(#"item.purchaseDate is %#", self.item.purchaseDate); <-- this returns NULL
NSError *error = nil;
NSManagedObjectContext *moc = _coreDataController.mainThreadContext;
if (![moc save:&error])
{
[[NSApplication sharedApplication] presentError:error];
}
}
}
I found the answers here very helpful, but this post really got me thinking. So today, the code looks like below, and it works great!!
1.
[itemArrayController setValue: [DatePicker1 dateValue] forKeyPath: #"selection.date1"];
2.
if ([itemArrayController valueForKeyPath: #"selection.date1"] == NULL) {
date1 = [NSDate date];
[datePicker1 setDateValue: date1];
} else {
[datePicker1 setDateValue: [itemArrayController valueForKeyPath: #"selection.date1"]];
date1 = [itemArrayController valueForKeyPath: #"selection.date1"];
}

iphone:access default calendar and reminder on button click event

How to retrieve default calendar and reminder programmatically in ios, I have one simple project which have one button ,i want click on button to access the default reminder and calendar
I have done simple code for that but it is nort working properly
following is the my sample code
#import "ViewController.h"
#import <EventKit/EventKit.h>
#interface ViewController ()
#end
#implementation ViewController
- (IBAction)btn:(id)sender {
EKEventStore *eventStore=[[EKEventStore alloc]init];
EKEvent *event =[EKEvent eventWithEventStore:eventStore];
NSDate *startDate=[[NSDate alloc]init];
NSDate *endDate =[[NSDate alloc]init];
event.title=#"Title for new event";
event.startDate=startDate;
event.endDate=endDate;
event.allDay=YES;
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
// if (err == noErr){
// UIAlertView * alert = [[UIAlertView alloc]initWithTitle:#"Event create" message:#"how about that?" delegate:nil cancelButtonTitle:#"okey" otherButtonTitles:nil];
//
// [alert show];
}
When I'm running it on iphone 4s reale device on that time it show's me the following error:
2013-03-13 09:52:22.638 remind[774:907] defaultCalendarForNewEvents
failed: Error Domain=EKCADErrorDomain Code=1013 "The operation
couldn’t be completed. (EKCADErrorDomain error 1013.)"
this is my .h header file where u have to declare this below code:
uikit framework
#import <UIKit/UIKit.h>
#import <EventKitUI/EventKitUI.h>
#define ALERT_Reminder 0
#interface GaSchedulesDeWorming : UIViewController<UITableViewDataSource, UITableViewDelegate, EKEventEditViewDelegate>
{
EKEventStore *eventStore;
}
this ins my implementation file .m:
**#import <EventKitUI/EventKitUI.h>**
add these package
this below code is for open the by default calender for set the reminde in ipone
EKEventStore *eventStore=[[EKEventStore alloc]init];
EKEvent *event =[EKEvent eventWithEventStore:eventStore];
NSDate *startDate=[[NSDate alloc]init];
NSDate *endDate =[[NSDate alloc]init];
event.title=#"Title for new event";
event.startDate=startDate;
event.endDate=endDate;
event.allDay=YES;
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
eventStore=[[EKEventStore alloc]init];
__block BOOL accessGranted = NO;
if([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)]) {
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
accessGranted = granted;
dispatch_semaphore_signal(sema);
}];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
} else {
accessGranted = YES;
}
if (accessGranted) {
}
EKEventEditViewController *controller = [[EKEventEditViewController alloc]init];
}

UIActivityViewController

I have a problem with the UIActivityViewController on iPad
Here is my Code:
NSString* someText = #"Hi, I am using the official iEveryThing Tech app #iEveryTech";
NSString* Website = [NSURL URLWithString:#"https://itunes.apple.com/us/app/ieverytech/id578148847?l=de&ls=1&mt=8"];
NSArray* dataToShare = #[someText,Website];
Class activityViewController = NSClassFromString(#"UIActivityViewController");
if(activityViewController) {
UIActivityViewController* activityViewController =
[[UIActivityViewController alloc] initWithActivityItems:dataToShare
applicationActivities:nil];
[self presentViewController:activityViewController animated:YES completion:nil];}
}
On iPhone the Mail composer View will disappear after sending the mail but not the Composer on the iPad here is my Composer:
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"error"
message:[NSString stringWithFormat:#"error %#", [error description]]
delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
[self dismissModalViewControllerAnimated:YES];
}
else {
[self dismissModalViewControllerAnimated:YES];
}
}
The activityViewController use a native method for send mail don't need use mailComposeController, like this
NSMutableArray *items = [NSMutableArray new];
[items addObject:#"text for share"];
[items addObject:[UIImage imageWithData:[NSData dataWithContentsOfFile:self.imagePath]]];
NSArray *activityItems = [NSArray arrayWithArray:items];
self.activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:[NSArray arrayWithObjects:whatsapp,instagram, nil]];
self.activityVC.excludedActivityTypes = #[UIActivityTypeAssignToContact, UIActivityTypePrint,UIActivityTypeAirDrop,UIActivityTypeCopyToPasteboard];
[self presentViewController:self.activityVC animated:YES completion:nil];
First thing, when using the activityViewController, your class is not the delegate for the mail composer and the code will not be called. This is all handled internally in the activityViewController.
As for your view not being dismissed, implement the complete block call for the activityViewController. In the block be sure to dismiss the view controller.

Can i use NSTimer in background?

I use
NSString *urlStr=[NSString stringWithFormat: #"http://xxx.xxx.xxx.xxx:8080/fft/getautodisplaydelay"];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Delay is %#",result);
timer = [NSTimer scheduledTimerWithTimeInterval:(5)
target:self
selector:#selector(loginunlogin:)
userInfo:nil
repeats:YES];
UILocalNotification *localNotif =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
}
-(void) loginunlogin:(NSTimer *)theTimer{
NSString *urlStr=[NSString stringWithFormat: #"http://xxx.xxx.xxx.xxx:8080/fft/getautodisplaydelay"];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Delay is %#",result);
delay=[result floatValue];
if([result isEqual:#"false"]==TRUE){
NSLog(#"Delay %#",result);
}else{
NSLog(#"User logged delay is %#",result);
[timer invalidate];
timer=nil;
delay=[result floatValue];
NSTimer *timer1 = [NSTimer scheduledTimerWithTimeInterval: delay target:self selector:#selector(targetMethod:)
userInfo:nil repeats:YES];
}
}
-(void) targetMethod: (NSTimer*)theTimer {
mapView =[[MKMapView alloc] init];
mapView.showsUserLocation=YES;
float mylo =mapView.userLocation.coordinate.longitude;
float myla =mapView.userLocation.coordinate.latitude;
NSString *str1 =[[NSString alloc] initWithFormat:#"%f",mylo];
NSString *str2 =[[NSString alloc] initWithFormat:#"%f",myla];
NSLog(#"longi %#",str1);
NSLog(#"latit %#",str2);
NSString *req=[NSString stringWithFormat: #"http://xxx.xxx.xxx.xxx:8080/fft/messages/getnewmessagescount?longitude=%#&latitude=%#",str1,str2];
NSURL *url = [NSURL URLWithString:req];
NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy : NSURLRequestReloadIgnoringCacheData timeoutInterval : 60.0 ] autorelease ];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",request);
if ([result isEqual: #"0"])
{
NSLog(#"No messages");
}else{
if ([result isEqual:#"false"]) {
NSLog(#"Not logged");
}else{
NSString *path = [NSString stringWithFormat:#"%#%#",
[[NSBundle mainBundle] resourcePath],
#"/tada.wav"];
//declare a system sound id
SystemSoundID soundID;
//Get a URL for the sound file
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
//Use audio sevices to create the sound
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
//Use audio services to play the sound
AudioServicesPlaySystemSound(soundID);
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
// Get the current date
NSDate *Date = [NSData date];
// Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:Date];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:Date];
// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
// Notification will fire in one minute
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = [[NSString alloc] initWithFormat:#"Your have got (%#) new messages",result];
// Set the action button
localNotif.alertAction = #"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:#"someValue" forKey:#"someKey"];
localNotif.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release]; NSLog(#"bla %#",result);
}}
}
How to change code that it works in background
I am using this code to play the sound when my application enter into background you can customize it for your own use
- (void)applicationDidEnterBackground:(UIApplication *)application{
backgroundTask = [application beginBackgroundTaskWithExpirationHandler: ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (backgroundTask != UIBackgroundTaskInvalid)
{
[application endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[NSThread sleepForTimeInterval:3];
[self startPlayingInBackground:#"default.aif"];
NSLog(#"Time remaining: %f",[application backgroundTimeRemaining]);
dispatch_async(dispatch_get_main_queue(), ^{
if (backgroundTask != UIBackgroundTaskInvalid)
{
// if you don't call endBackgroundTask, the OS will exit your app.
[application endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}
});
});
}
The line below is the code with help of which m playing the sound it's my objective c function all
[self startPlayingInBackground:#"default.aif"];

Resources