How to turn On Off Notificiation form app with using component UISwitch.
From setting if user turn On/Off Notification of any specific application UISwitch is turn On/Off using
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationEnteredForeground:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
- (void)applicationEnteredForeground:(NSNotification *)notification {
NSLog(#"Application Entered Foreground");
[self notificationEnableDisable];
}
-(void)notificationEnableDisable{
NSString *iOSversion = [[UIDevice currentDevice] systemVersion];
NSString *prefix = [[iOSversion componentsSeparatedByString:#"."] firstObject];
float versionVal = [prefix floatValue];
if (versionVal >= 8)
{
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types != UIUserNotificationTypeNone)
{
NSLog(#" Notification ON");
[self.switch_DailyNotification setOn:YES];
}
else
{
[self.switch_DailyNotification setOn:NO];
NSLog(#" Notification OFF");
}
}
else
{
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types != UIRemoteNotificationTypeNone)
{
NSLog(#"Notification ON");
[self.switch_DailyNotification setOn:YES];
}
else
{
[self.switch_DailyNotification setOn:NO];
NSLog(#" Notification OFF");
}
}
}
This above code work fine when user turn On/Off Notification from IPhone setting.
How to implement from application to turn On/Off Notification which is in IPhone setting?
Note: This is for LocalNotification not for PushNotification!
You can't do that due to apple restrictions it doesn't matter if its local or push notification:
https://stackoverflow.com/a/10510610/8873550
Related
Example:-
I have generated 4 local notifications with 4 types in minimize State.
Type of notifications below.
Message
Friend Request
Video call
Audio call
notifications are shown in notification center.
Noow..I have clicked on 2nd notification,
How can i get which number of notification clicked?
How can i get 2nd notification body alert text(content)?
this mehod is not working for minimize state
like whatsApp.. I need to go on specific screen according to Notification type.
- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type {
NSString *Notitype=#"";
if ([[payload.dictionaryPayload valueForKey:#"type"]isEqualToString:#"video"]) {
Notitype=#"video";
}
else if ([[payload.dictionaryPayload valueForKey:#"type"]isEqualToString:#"friendRequest"]) {
Notitype=#"friend Request";
}
else if([[payload.dictionaryPayload valueForKey:#"type"] isEqualToString:#"message"] )
{
Notitype=#"message";
}
else{
Notitype=#"audio";
}
I'm creating UILocalNotification like this :
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:Notitype];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
[[UIApplication sharedApplication] setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
For Set local notification as:
// Schedule the notification
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:Notitype];
[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[notification setTimeZone:[NSTimeZone defaultTimeZone]];
//Create user info for local notification.
NSDictionary* dict = #{#"Type": #"message", #"ID": #"set your unique ID", #"body": notification.alertBody,};
notification.userInfo = dict;
//You can Set Type as: message, friend Request, video call, Audio call.
[[UIApplication sharedApplication] setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
for get which type of local notifications is click than you can use didReceiveLocalNotification delegate.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
//[super application:application didReceiveLocalNotification:notification]; // In most case, you don't need this line
//Get notification type
NSString *notificationType = [notification.userInfo valueForKey:#"Type"];
//notificationType as: message, friend Request, video call, Audio call.
NSString *notificationBody = [notification.userInfo valueForKey:#"Notification_body"];
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {
// Application in foreground when notification is delivered.
if ([notificationType isEqual:#"message"]) {
//Handle message
} else if ([notificationType isEqual:#"friend Request"]) {
//Handle friend Request
} else if ([notificationType isEqual:#"video call"]) {
//Handle video call
} else if ([notificationType isEqual:#"Audio call"]) {
//Handle Audio call
}
} else if (state == UIApplicationStateBackground) {
// Application was in the background when notification was delivered.
if ([notificationType isEqual:#"message"]) {
//Handle message
} else if ([notificationType isEqual:#"friend Request"]) {
//Handle friend Request
} else if ([notificationType isEqual:#"video call"]) {
//Handle video call
} else if ([notificationType isEqual:#"Audio call"]) {
//Handle Audio call
}
} else {
}
}
Update
Also check this same things in DidFinishLaunchingWithOptions, possible user don't react on notification, but tap on App icon to open app. So in case of video call or anything urgent then it must be handled through DidFinishLaunchingWithOptions
My problem is, if app is in background and notification arrives and I opened the app from icon; app restores it states but I want to update the screen data in this case. Is there any way to update the data in background when notification arrives?
Here is the code which I'm using for tackling this case:
ViewController.m file code:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(appIsComingFromBackground:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
// Do any additional setup after loading the view, typically from a nib.
}
- (void) appIsComingFromBackground:(NSNotification *) note {
// code
NSString *hasMessage = [[NSUserDefaults standardUserDefaults] objectForKey:#"alertmsg"];
if([hasMessage length]!=0)
{
_labelText.text = hasMessage;
[[NSUserDefaults standardUserDefaults] setObject:#"" forKey:#"alertmsg"];
}
else{
_labelText.text = #"";
}
}
AppDelegate.m file code:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
if (application.applicationState == UIApplicationStateActive) {
}
else if(application.applicationState == UIApplicationStateBackground || application.applicationState == UIApplicationStateInactive)
{
[[NSUserDefaults standardUserDefaults] setObject:notification.alertTitle forKey:#"alertmsg"];
}
NSLog(#"Alert Message: %#", notification.alertTitle);
NSLog(#"Alert Body: %#", notification.alertBody);
}
Application is NOT Running
When the app is not running, users see notifications in the following ways, depending on the notification settings:
Displaying an alert or banner
Badging the app icon
Playing a sound
By tapping on action button of the notification, users will launch the app. In this case, the application:didFinishLaunchingWithOptions: method of the application delegate is called.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
// Handle launching from a notification
UILocalNotification *locationNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (locationNotification) {
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
}
return YES;
}
Applicaton is Running in Foreground
If the app is running while the notification is delivered, there is no alert displayed on screen. The application automatically calls its delegate’s application:didReceiveLocalNotification: method.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {
}
// Request to reload table view data
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadData" object:self];
// Set icon badge number to zero
application.applicationIconBadgeNumber = 0;
}
Application is Running in Background
The app has been launched before but users switch to another app. When the notification is fired, users normally see an alert banner at the top of the screen. When it’s tapped, the app will be brought to the foreground. Similar to the case that the app is running in foreground, the application automatically calls its delegate’s application:didReceiveLocalNotification: method.
In Appdelegate
- (void)application:(UIApplication *)application didReceiveLocalNotification: (UILocalNotification *)notification
{
if (application.applicationState == UIApplicationStateActive) {
}
else if(application.applicationState == UIApplicationStateBackground || application.applicationState == UIApplicationStateInactive)
{
// [[NSUserDefaults standardUserDefaults] setObject:notification.alertTitle forKey:#"alertmsg"];
[[NSNotificationCenter defaultCenter]postNotificationName:#"PushNotificationReceived" object:nil userInfo:userInfo];
}
NSLog(#"Alert Message: %#", notification.alertTitle);
NSLog(#"Alert Body: %#", notification.alertBody);
}
In view controller:
-(void)viewDidLoad
{
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(doChangesWhatdidYouWant:) name:#"PushNotificationReceived" object:nil];
}
-(void)doChangesWhatdidYouWant:(NSNotification *)notification{
//Todo
}
Hi i am new for push notification and i am working on a project there push notification have been used ,
i understand all code but not [[userInfo objectForKey:#"payload"] objectForKey:#"userId"]] where it can store value in userinfo ??
- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary*) userInfo {
**if ([self.profileManager.profile.userId isEqualToString:[[userInfo objectForKey:#"payload"] objectForKey:#"userId"]]**) {
if (application.applicationState == UIApplicationStateActive) {
UIRemoteNotificationType apnsType = [application enabledRemoteNotificationTypes];
if(apnsType != UIRemoteNotificationTypeNone) {
if((apnsType & UIRemoteNotificationTypeAlert) != 0) {
[self showNotificationAlert:userInfo];
}
if((apnsType & UIRemoteNotificationTypeBadge) != 0) {
NSString* badge = [userInfo valueForKey:#"badge"];
application.applicationIconBadgeNumber = [badge intValue];
}
}
} else {
NSString* event = [[userInfo objectForKey:#"payload"] objectForKey:#"event"];
if ([event isEqualToString:#"QUESTION_ANSWERED"]) {
[self presentYouAsked];
} else if ([event isEqualToString:#"QUESTION_ASKED"]) {
[self presentFriendsAsked];
}
}
}
}
The userInfo dictionary is part of the push notification data that was received. The line you refer to extracts another dictionary, associated with the key "payload" from the push notification dictionary and then looks for the value associated with the key "userid" in that dictionary.
At a guess that "if" statement it determining whether the push notification that was received applies to the current user on this device.
I am creating a Chat kind of iPhone application using Apple push notification services. APN's is working fine and i am getting notification when user is receiving new message. So, i have set one Toast pop up in didReceiveRemoteNotification of my App Delegate class. The problem is, i am getting Toast pop up in every View Controller screen because i have added Toast on my main window itself. but can you please help me that how can i hide this Toast pop up from one of my Chat List View Controller screen. How can i check which View Controller is loaded currently on my window view, when application is in foreground?
here is my code :
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{
if ( application.applicationState == UIApplicationStateActive ){
NSString *personName = [[userInfo valueForKey:#"aps"] valueForKey:#"user_name"];
NSString *meassge = [NSString stringWithFormat:#"New message from %#.", personName];
[[self window] makeToast:meassge duration:1.0 position:#"center"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadTheTable" object:nil];
}
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
Thanks!
Declare below methods in AppDelegate.m
- (UIViewController*)topViewController {
return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}
- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
if ([rootViewController isKindOfClass:[UITabBarController class]]) {
UITabBarController* tabBarController = (UITabBarController*)rootViewController;
return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
} else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
UINavigationController* navigationController = (UINavigationController*)rootViewController;
return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
} else if (rootViewController.presentedViewController) {
UIViewController* presentedViewController = rootViewController.presentedViewController;
return [self topViewControllerWithRootViewController:presentedViewController];
} else {
return rootViewController;
}
}
- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{
if ( application.applicationState == UIApplicationStateActive ){
NSString *personName = [[userInfo valueForKey:#"aps"] valueForKey:#"user_name"];
NSString *meassge = [NSString stringWithFormat:#"New message from %#.", personName];
if(![[self topViewController] isKindOfClass:[ChatListViewController class]])//ChatListViewController is your viewcontroller
[[self window] makeToast:meassge duration:1.0 position:#"center"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadTheTable" object:nil];
}
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
- (IBAction)buttonPressed:(id)sender
{
UIDevice *device = [UIDevice currentDevice];
device.batteryMonitoringEnabled = YES;
if ([[UIDevice currentDevice] isMultitaskingSupported]) {
[self beingBackgroundUpdateTask];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(batteryChanged:) name:#"UIDeviceBatteryLevelDidChangeNotification" object:device];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(batteryChanged:) name:#"UIDeviceBatteryStateDidChangeNotification" object:device];
[self currentBatteryState];
}
- (void) beingBackgroundUpdateTask
{
self->backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUpdateTask];
}];
}
- (void) endBackgroundUpdateTask
{
[[UIApplication sharedApplication] endBackgroundTask: self->backgroundUpdateTask];
self->backgroundUpdateTask = UIBackgroundTaskInvalid;
}
For some reason, the notification's are not being observed. Am i doing something wrong? I want to observe for unto 10 minutes when unplugged
You shouldn't be calling endBackgroundUpdateTask in your buttonPressed: method, since that cancels your background task. Try removing this code:
if ([[UIDevice currentDevice] isMultitaskingSupported]) {
[self endBackgroundUpdateTask];
}
Also, you should pass the UIDeviceBatteryLevelDidChangeNotification constant to the "name" parameter, not the string. It should look like this (note the lack of double quotes):
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(batteryChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:device];
(It's also possible that UIDevice simply doesn't send those notifications in the background.)
Have you added the applicable backgrounding code to your AppDelegate? Here are backgrounding instructions in the iOS Programming Guide