Can I use iOS' local pushnotification in OSX - macos

Is there a way to get iOS' Local PushNotification to work on OSX? I have an program that I would like to receive scheduled notifications from the local computer even if the program is closed.

This is for local notification
- (void)scheduleNotificationWithItem:(ToDoItem *)item interval:(int)minutesBefore {
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:item.day];
[dateComps setMonth:item.month];
[dateComps setYear:item.year];
[dateComps setHour:item.hour];
[dateComps setMinute:item.minute];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = [itemDate addTimeInterval:-(minutesBefore*60)];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody =#"Local Notification";
localNotif.alertAction = NSLocalizedString(#"View Details", nil);
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:item.eventName forKey:ToDoItemKey];
localNotif.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
}

All you need is here : https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Notifications

Related

Pause and Resume Time Xcode

I know that there is no way to pause a timer using NSTimer. I know i have to store the date and call it again. I have tried every solution and i cannot find any that have successfully worked. So my question is, does anyone know how to pause and resume?
This worked good for me.
Created 2 UIButtons ('startButton' & 'resetButton'), a UILabel to display time ('timeLabel'), NSTimeInterval ('pauseTimeInterval'), NSTimer (stopWatchTimer') and used the following code:
NSDate *pauseStart, *previousFireDate, *startDate;
NSTimeInterval pauseTimeInterval;
NSTimer *stopWatchTimer;
-(void)pauseTimer{
pauseStart = [NSDate dateWithTimeIntervalSinceNow:0];
previousFireDate = [self fireDate];
[self setFireDate:[NSDate distantFuture]];
}
-(void)resumeTimer{
float pauseTime = -1*[pauseStart timeIntervalSinceNow];
[self setFireDate:[previousFireDate initWithTimeInterval:pauseTime sinceDate:previousFireDate]];
}
-(IBAction)startTime:(id)sender {
//start timer
if ([startButton.titleLabel.text isEqualToString:#"Start"] && (![self.stopWatchTimer isValid]) && ([timeLabel.text isEqualToString:#"00:00:00"]))
{
[startButton setTitle:#"Stop" forState:UIControlStateNormal];
startDate = [NSDate date];
startDate = [startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))];
self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:#selector(updateTimer)
userInfo:nil
repeats:YES];
resetButton.hidden = YES;
}
//pause timer
else if (([self.stopWatchTimer isValid]) && ([startButton.titleLabel.text isEqualToString:#"Stop"]))
{
[startButton setTitle:#"Resume" forState:UIControlStateNormal];
[self.stopWatchTimer pauseTimer];
resetButton.hidden = NO;
}
//resume timer
else {
[startButton setTitle:#"Stop" forState:UIControlStateNormal];
startDate = [NSDate date];
startDate = [startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))];
[self.stopWatchTimer resumeTimer];
resetButton.hidden = YES;
}
}
-(IBAction)resetTime:(id)sender {
[self.stopWatchTimer invalidate];
self.stopWatchTimer = nil;
self.timeLabel.text = #"00:00:00";
[startButton setTitle:#"Start" forState:UIControlStateNormal];
pauseTimeInterval = 0.0;
resetButton.hidden = YES;
}
-(void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
self.timeLabel.text = timeString;
pauseTimeInterval = timeInterval;
}

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);

Crash Occurring on First Launch When populating core data database

I keep getting an error in the debugger for my application saying,
2013-06-23 16:07:15.826 collection view recipies[5681:c07] -[NSManagedObject length]: unrecognized selector sent to instance 0x9495280
2013-06-23 16:07:15.827 collection view recipies[5681:c07] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObject length]: unrecognized selector sent to instance 0x9495280'
* First throw call stack:
(0x26ac012 0x1517e7e 0x27374bd 0x269bbbc 0x269b94e 0x2b11c4 0x16d80a 0x4464 0x64f2da 0x6508f4 0x652b91 0x19c2dd 0x152b6b0 0x18eefc0 0x18e333c 0x18eeeaf 0x23b2bd 0x183b56 0x18266f 0x182589 0x1817e4 0x18161e 0x1823d9 0x1852d2 0x22f99c 0x17c574 0x17c76f 0x17c905 0x185917 0x14996c 0x14a94b 0x15bcb5 0x15cbeb 0x14e698 0x2c06df9 0x2c06ad0 0x2621bf5 0x2621962 0x2652bb6 0x2651f44 0x2651e1b 0x14a17a 0x14bffc 0x1e9d 0x1dc5)
libc++abi.dylib: terminate called throwing an exception
In My application delegate, if check to see if the application is being launched for the first time, and if it is, I then add several image paths to the core data structure.
In AppDelegate.m under ApplicationDidFinishLaunchingWithOptions,
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"HasLaunchedOnce"])
{
// app already launched
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"HasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
// This is the first launch ever
NSArray *mainDishImages = [NSArray arrayWithObjects:#"egg_benedict.jpg", #"full_breakfast.jpg", #"ham_and_cheese_panini.jpg", #"ham_and_egg_sandwich.jpg", #"hamburger.jpg", #"instant_noodle_with_egg.jpg", #"japanese_noodle_with_pork.jpg", #"mushroom_risotto.jpg", #"noodle_with_bbq_pork.jpg", #"thai_shrimp_cake.jpg", #"vegetable_curry.jpg", nil];
NSArray *drinkDessertImages = [NSArray arrayWithObjects:#"angry_birds_cake.jpg", #"creme_brelee.jpg", #"green_tea.jpg", #"starbucks_coffee.jpg", #"white_chocolate_donut.jpg", nil];
for (NSString *imagePath in mainDishImages) {
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newRecipe = [NSEntityDescription insertNewObjectForEntityForName:#"Recipe" inManagedObjectContext:context];
[newRecipe setValue:imagePath forKey:#"imageFilePath"];
}
for (NSString *imagePath in drinkDessertImages) {
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newRecipe = [NSEntityDescription insertNewObjectForEntityForName:#"Deserts" inManagedObjectContext:context];
[newRecipe setValue:imagePath forKey:#"imageFilePath"];
}
}
And I access that data in my collectionViewController, I access that data.
- (NSManagedObjectContext *)managedObjectContext{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Deserts"];
deserts = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSFetchRequest *fetchRequestTwo = [[NSFetchRequest alloc] initWithEntityName:#"Recipe"];
meals = [[managedObjectContext executeFetchRequest:fetchRequestTwo error:nil] mutableCopy];
recipeImages = [NSArray arrayWithObjects:meals, deserts, nil];
[self.collectionView reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Deserts"];
deserts = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSFetchRequest *fetchRequestTwo = [[NSFetchRequest alloc] initWithEntityName:#"Recipe"];
meals = [[managedObjectContext executeFetchRequest:fetchRequestTwo error:nil] mutableCopy];
recipeImages = [NSArray arrayWithObjects:meals, deserts, nil];
UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
collectionViewLayout.sectionInset = UIEdgeInsetsMake(5, 0, 5, 0);
self.navigationController.navigationBar.translucent = YES;
self.collectionView.contentInset = (UIEdgeInsetsMake(44, 0, 0, 0));
selectedRecipes = [NSMutableArray array];
}
According to crashalytics, the error is in the line where it says
recipeImageView.image = [UIImage imageNamed:[recipeImages[indexPath.section] objectAtIndex:indexPath.row]];
In the method
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = [UIImage imageNamed:[recipeImages[indexPath.section] objectAtIndex:indexPath.row]];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame"]];
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame-selected.png"]];
return cell;
}
I hope you can help. Thanks In Advance!
The UIImage method imageNamed takes an NSString as argument, but you pass a NSManagedObject to it.
You should get the image path from the managed object first. Try this:
id managedObject = [recipeImages[indexPath.section] objectAtIndex:indexPath.row];
NSString* imagePath = [managedObject valueForKey:#"imageFilePath"];
recipeImageView.image = [UIImage imageNamed:imagePath];

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
}

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