iphone:access default calendar and reminder on button click event - xcode

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

Related

UIAlertController Warning Message

I am using the below code for UIAlertController in my project.
if([[[UIDevice currentDevice] systemVersion]floatValue] >= 8.0){
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:#"Input Error"
message:#"Please enter a valid email."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* okAction = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Input Error"
message:#"Please enter a valid email"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alertView show];
}
I am getting the below waring message:
Warning: Attempt to present <UIAlertController: 0x7f8da58df1f0> on <MBComplaintsViewController: 0x7f8da36454d0> which is already presenting (null)
Kindly guide me how to properly use UIAlertController using Objective C.
Thanks,
Abin Koshy Cheriyan
Yes as per #Alexander you should not be dismissing the alert controller like this explicitly.
As per an apple engineer a new window gets added each time an UIAlertController is displayed so when we go for dismissing it the window is still there though the alert controller disappears.
So there are two ways to handle this -
Way 1 - No explicit dismiss
Do not explicitly dismiss the UIAlertController, let it be done by the user
Way 2 - Use your own window
Simply create a category on UIAertController
Here is the sample code -
.h
#import <UIKit/UIKit.h>
#interface UIAlertController (MyAdditions)
#property(nonatomic,strong) UIWindow *alertWindow;
-(void)show;
#end
In .m
#import "UIAlertController+MyAdditions.h"
#import <objc/runtime.h>
#implementation UIAlertController (MyAdditions)
#dynamic alertWindow;
- (void)setAlertWindow:(UIWindow *)alertWindow {
objc_setAssociatedObject(self, #selector(alertWindow), alertWindow, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIWindow *)alertWindow {
return objc_getAssociatedObject(self, #selector(alertWindow));
}
- (void)show {
self.alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.alertWindow.rootViewController = [[UIViewController alloc] init];
// window level = topmost + 1
UIWindow *topWindow = [UIApplication sharedApplication].windows.lastObject;
self.alertWindow.windowLevel = topWindow.windowLevel + 1;
[self.alertWindow makeKeyAndVisible];
[self.alertWindow.rootViewController presentViewController:self animated:YES completion:nil];
}
-(void)hide {
self.alertWindow.hidden = YES;
self.alertWindow = nil;
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
// just to ensure the window gets desroyed
self.alertWindow.hidden = YES;
self.alertWindow = nil;
}
To show the alert controller
UIAlertCntroller *alert = ## initialisation##;
// will show the alert
[alert show];
//to dismiss
[alert hide];
[alert dismissViewControllerAnimated:YES completion:nil];
Even you can checkout one of my sample implementation here
I don't know about your problem, but you shouldn't do that
handler:^(UIAlertAction * action)
{
[alert dismissViewControllerAnimated:YES completion:nil];
}];
It will be anyway dismissed on any of your actions.

xcode How to link UIAlertview action to another viewcontroller?

Im am trying to link one of my buttons from the UIAlertView that pops up so that It changes to another viewcontroller. Basically, the cancel already works, but when Next is clicked it doesnt, and i don't know how to link to another viewcontroller. Please help.
#import "ViewController.h"
#interface ViewController() <UIAlertViewDelegate>
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)clickButton:(id)sender {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Test" message: #"Message" delegate: self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Redeem", nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex == 1){ //Next
UIViewController* newView = [[UIViewController alloc] init];
[self presentViewController:newView animated:YES completion:nil];
}
}
#end
It is working...Just create object of viewcontroller that you want to present instead of
UIViewController* newView = [[UIViewController alloc] init];
like
SecondViewController * newView = [[SecondViewController alloc] initWithNibName:#"SecondViewController" bundle:nil];
if you are using xib.
Or
SecondViewController * newView = [self.storyboard instantiateViewControllerWithIdentifier:#"SecondViewController"];
if you are using storyboard(if you want to go through coding).
and then write
[self presentViewController:newView animated:YES completion:nil];
line.

Retrieving Int Value from Parse for Xcode and displaying it in a label

bit of a beginner here and I've been stuck on something all day!
I've got 2 Parse Tables: a User (which works perfectly for logging in etc) and a UserStats that holds variables (in this case the User's Level as the first column)
All I want to do is retrieve the User's current level and display it in a label in Xcode. I've done lots of research but I cannot work out where I've gone wrong.
I'm using this Query in my .m:
- (void) retrieveFromParse {
PFQuery query = [PFQuery queryWithClassName:#"UserStats"];
[query whereKey:#"User" equalTo:[PFUser currentUser]];
[query getFirstObjectInBackgroundWithBlock:(PFObjectobject, NSError *error)
{
if (!object)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oh No!" message:#"Could not locate value!" delegate:self cancelButtonTitle:#"Okay" otherButtonTitles:nil];
[alert show];
}
else
{
int Level = [[object objectForKey:#"Level"] intValue];
[_newlabel setText:[NSString stringWithFormat:#"%d", Level]];
}
}];
}
and my .h looks like this:
import <UIKit/UIKit.h>
import <Parse/Parse.h>
#interface ShowLevel : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *newlabel;
#end
Edit: I've turned on exception breakpoints and it's highlighting:
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
What is the actual error that you are getting? Also you have to do anything that has to do with UI on the main thread. The query is actually running on the background thread and you are either showing alertView or updating a label which you have to do on the main thread. Add dispatch_async(dispatch_get_main_queue(), ^{ }); to your code where you are doing UI
if (!object)
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Oh No!" message:#"Could not locate value!" delegate:self cancelButtonTitle:#"Okay" otherButtonTitles:nil];
[alert show];
});
}
else
{
int Level = [[object objectForKey:#"Level"] intValue];
dispatch_async(dispatch_get_main_queue(), ^{
[_newlabel setText:[NSString stringWithFormat:#"%d", Level]];
});
}
This has since been resolved. I used the .m code:
PFQuery *query = [PFQuery queryWithClassName:#"UserStats"];
PFObject *Object = [query getObjectWithId:#"fghsd7fddhf"];
level = [[Object objectForKey:#"Level"] intValue];
[levelLabel setText:[NSString stringWithFormat:#"%i", level]];
While it's only temporary since I'll need to change it to point to values without specifying objectId, this works nicely for testing. Thanks to everyone who provided help :)

Unable to save images in Core Data

I am creating a student index app, in which you can save names, pictures and roles of students. Everything works just fine, but my code does not save images in my Core Data Model. I have been trying to figure it out the whole day.
You can find my whole project here: http://www21.zippyshare.com/v/26184330/file.html
#import "AddStudent.h"
#import "Studenten.h"
#import "Bild.h"
#import <QuartzCore/QuartzCore.h>
#interface AddStudent () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
#end
#implementation AddStudent;
#synthesize delegate;
#synthesize managedObjectContext = _managedObjectContext;
#synthesize selectedBetreuungsgrund;
#synthesize studentBetrGrundCell = _studentBetrGrundCell;
#synthesize vorschauImageView = _vorschauImageView;
- (void)viewWillAppear:(BOOL)animated {
_studentBetrGrundCell.textLabel.text = #"";
_studentBetrGrundCell.delegate = self;
_studentBetrGrundCell.managedObjectContext = self.managedObjectContext;
}
- (void)betrGrundWasSelectedOnPicker:(Betreuungsgrund *)betreuungsgrund {
self.selectedBetreuungsgrund = betreuungsgrund;
_studentBetrGrundCell.textLabel.text = self.selectedBetreuungsgrund.name;
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)dismissKeyboard {
[self.view endEditing:TRUE];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.studentNachnameTextfeld.delegate = self;
self.studentVornameTextFeld.delegate = self;
_studentNachnameTextfeld.autocapitalizationType = UITextAutocapitalizationTypeSentences;
_studentVornameTextFeld.autocapitalizationType = UITextAutocapitalizationTypeSentences;
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(dismissKeyboard)];
[tgr setCancelsTouchesInView:NO];
[self.tableView addGestureRecognizer:tgr];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
- (IBAction)save:(id)sender
{
if (([_studentNachnameTextfeld.text isEqualToString:(#"")])||([_studentVornameTextFeld.text isEqualToString:(#"")])){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:#"Sie müssen alle Namensfelder ausfüllen!" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
else {
Student *student = [NSEntityDescription insertNewObjectForEntityForName:#"Student"
inManagedObjectContext:self.managedObjectContext];
student.vorname = _studentVornameTextFeld.text;
student.name = _studentNachnameTextfeld.text;
student.hatBetrGrund = selectedBetreuungsgrund; //Funzt trotzdem
student.bild.vorschauData = _vorschauImageView.image;
NSLog(#"Image Core Data: %#", _vorschauImageView.image);
NSLog(#"Image Core Data DB: %#", student.bild.vorschauData);
// NSLog(#"Betreuungsgrund: %#", student.hatBetrGrund);
[self.managedObjectContext save:nil]; // Eintrag in Datenbank
[self.delegate AddStudentSavePressed:self];
NSLog (#"Save Button bei AddBetrGrund pressed");
}
}
- (IBAction)albumButtonPressed:(id)sender
{
if (! [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary] ) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Es steht kein Album zur Verfügung!" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
return;
}
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.delegate = self;
controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:controller animated:YES completion:nil];
}
- (IBAction)kameraButtonPressed:(id)sender
{
if (! [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] ) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Es steht keine Kamera zur Verfügung!" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
return;
}
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.delegate = self;
controller.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:controller animated:YES completion:nil];
}
- (IBAction)deleteBildPressed:(id)sender {
self.vorschauImageView.image = nil;
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[picker dismissViewControllerAnimated:YES completion:nil];
_vorschauImageView.image = image;
_vorschauImageView.layer.cornerRadius = 10; // abgerundete Ecken
NSLog(#"Image Vorschau: %#", _vorschauImageView.image);
}
Thanks in advance for ur help. Cheers
Generally you shouldn't save the image in Core Data. Instead, save it in a file on disk and save the path to the file in Core Data model.
This line:
student.bild.vorschauData = _vorschauImageView.image;
makes it look like the student has a relationship (bild) to some other object which contains the image. You need to create that object, insert it into the context and associated it with the student before you can use it.

Xcode check error to manage event

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
}

Resources