I want to check "Push Notification option" in iOS device, any time if the application is running (or ON from resume mode). I use the following code to check, if the option is OFF:
-(void)PushNotificationServiceChecking
{
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types == UIRemoteNotificationTypeNone)
{
NSString *msg = #"Please press ON to enable Push Notification";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Push Notification Service Disable" message:msg delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"ON", nil];
alert.tag = 2;
[alert show];
}
}
Then i use the following code for going to the "Settings tab >> Notification center", so that user can on it manually :
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 2)
{
if (buttonIndex == 0)
{
// this is the cancel button
}
else if (buttonIndex == 1)
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert)];
}
}
}
But, now the problem that I am facing is, it only appears at the 1st time after launching the application. It works as I want. But after that, if I turn OFF the "Push Notification option" from "settings" it gives me no "Alert Message".
In iOS 8 you can now use:
[[UIApplication sharedApplication] isRegisteredForRemoteNotifications];
And to check how the settings are setup you could use:
[[UIApplication sharedApplication] currentUserNotificationSettings];
If the App once got registered with the registerForRemoteNotification, then you can disable as well as enable . Once you disable and you are about to Re-Regigister with it, then this will enable the registerForRemoteNotification, without Popup for a alert.
Technical Note TN2265: Troubleshooting Push Notifications
The first time a push-enabled app registers for push notifications, iOS
asks the user if they wish to receive notifications for that app. Once
the user has responded to this alert it is not presented again unless
the device is restored or the app has been uninstalled for at least a
day.
If you want to simulate a first-time run of your app, you can leave
the app uninstalled for a day. You can achieve the latter without
actually waiting a day by setting the system clock forward a day or
more, turning the device off completely, then turning the device back
on.
Fore More Info: INFO && Info 2
Edit : For checking with alert enable -
use
if (types & UIRemoteNotificationTypeAlert){}
instead of
if (types == UIRemoteNotificationTypeNone){}
Edit :
Latest update from the doc for iOS 8 or later, You can check out by :
- (BOOL)isRegisteredForRemoteNotifications
It's work for me. Hope this help! :D
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"8.0")){
UIUserNotificationType type = [[[UIApplication sharedApplication] currentUserNotificationSettings] types];
if (type == UIUserNotificationTypeNone){
ALERT_WITH_TITLE(#"", kMessageNotificationTurnOnRequire);
}
}
else {
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types == UIRemoteNotificationTypeNone) {
ALERT_WITH_TITLE(#"", kMessageNotificationTurnOnRequire);
}
}
NSString *iOSversion = [[UIDevice currentDevice] systemVersion];
NSString *prefix = [[iOSversion componentsSeparatedByString:#"."] firstObject];
float versionVal = [prefix floatValue];
if (versionVal >= 8)
{
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types != UIUserNotificationTypeNone)
{
NSLog(#" Push Notification ON");
}
else
{
NSString *msg = #"Please press ON to enable Push Notification";
UIAlertView *alert_push = [[UIAlertView alloc] initWithTitle:#"Push Notification Service Disable" message:msg delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Setting", nil];
alert_push.tag = 2;
[alert_push show];
NSLog(#" Push Notification OFF");
}
}
else
{
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types != UIRemoteNotificationTypeNone)
{
NSLog(#" Push Notification ON");
}
else
{
NSString *msg = #"Please press ON to enable Push Notification";
UIAlertView *alert_push = [[UIAlertView alloc] initWithTitle:#"Push Notification Service Disable" message:msg delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Setting", nil];
alert_push.tag = 2;
[alert_push show];
NSLog(#" Push Notification OFF");
}
}
Related
Hi in my app i have notification section and user can enable notifications using switch.After first launch when ever user on the switch i am getting don't allow or ok alertview from ios.If user select don't allow and switch will be off and user will not get notifications. Now if user try to on the switch i want to show an alert to user with text "Please enable notifications from settings".Can any one please suggest the way to do this.
For UILocalNotification permission check the following, types parameter value will be none incase user has not allowed it.
[[UIApplication sharedApplication] currentUserNotificationSettings]
You can check the the permission using isRegisteredForRemoteNotifications method.
- (void)checkForNotificationPermission
{
if (!([[UIApplication sharedApplication] isRegisteredForRemoteNotifications] && [self pushNotificationsEnabled]))
{
// Show alert here
}
}
// For fixing iOS 8 issue mentioned here http://stackoverflow.com/a/28441181/1104384
- (BOOL)pushNotificationsEnabled
{
if ([[UIApplication sharedApplication] respondsToSelector:#selector(currentUserNotificationSettings)])
{
UIUserNotificationType types = [[[UIApplication sharedApplication] currentUserNotificationSettings] types];
return (types & UIUserNotificationTypeAlert);
}
else
{
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
return (types & UIRemoteNotificationTypeAlert);
}
}
NSString *iOSversion = [[UIDevice currentDevice] systemVersion];
NSString *prefix = [[iOSversion componentsSeparatedByString:#"."] firstObject];
float versionVal = [prefix floatValue];
if (versionVal >= 8)
{
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types != UIUserNotificationTypeNone)
{
NSLog(#" Push Notification ON");
}
else
{
NSString *msg = #"Please press ON to enable Push Notification";
UIAlertView *alert_push = [[UIAlertView alloc] initWithTitle:#"Push Notification Service Disable" message:msg delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Setting", nil];
alert_push.tag = 2;
[alert_push show];
NSLog(#" Push Notification OFF");
}
}
else
{
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types != UIRemoteNotificationTypeNone)
{
NSLog(#" Push Notification ON");
}
else
{
NSString *msg = #"Please press ON to enable Push Notification";
UIAlertView *alert_push = [[UIAlertView alloc] initWithTitle:#"Push Notification Service Disable" message:msg delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Setting", nil];
alert_push.tag = 2;
[alert_push show];
NSLog(#" Push Notification OFF");
}
}
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIAp
plication sharedApplication] registerUserNotificationSettings:settings];
// [[UIApplicationsharedApplication]registerForRemoteNotifications];
if ([[UIApplication sharedApplication] respondsToSelector:#selector(currentUserNotificationSettings)]) {
UIUserNotificationType types = [[[UIApplication sharedApplication] currentUserNotificationSettings] types];
if (types == UIUserNotificationTypeNone) {
[_TransparentView setBackgroundColor:[[UIColor clearColor] colorWithAlphaComponent:0.8]];
lblDescription.text=#"Please enable notifications from settings.";
}
}
}
Try this code. It will work for iOS 8.0 later and before versions.
if (([[[UIDevice currentDevice] systemVersion] compare:8.0 options:NSNumericSearch] != NSOrderedAscending)) {
if (![[UIApplication sharedApplication] isRegisteredForRemoteNotifications])
{
DisplayAlert(#"Please enable Permission from Settings->App Name->Notifications->Allow Notifications");
return;
}
}
else{
UIRemoteNotificationType status = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (status == UIRemoteNotificationTypeNone)
{
DisplayAlert(#"Please enable Permission from Settings->App Name->Notifications->Allow Notifications");
return;
}
}
I have the following code which Im using to decide if the user has given permissions for local notifications:
UIUserNotificationSettings *grantedSettings = [[UIApplication sharedApplication] currentUserNotificationSettings];
if (grantedSettings.types == UIUserNotificationTypeNone) {
NSLog(#"No permission granted");
//IF AND ONLY IF alerts are wanted by raymio user! FIX
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Notice"
message:#"You need to enable notifications to be able to receive sun alerts!"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* OKAction = [UIAlertAction actionWithTitle:#"Go to Settings now" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:url];
}];
[alert addAction:OKAction];
UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:cancelAction];
[self.window addSubview:self.window.rootViewController.view];
[self.window makeKeyAndVisible];
[self.window.rootViewController presentViewController:alert animated:YES completion:nil];
}
else if (grantedSettings.types & UIUserNotificationTypeSound & UIUserNotificationTypeAlert ){
NSLog(#"Sound and alert permissions ");
}
else if (grantedSettings.types & UIUserNotificationTypeAlert){
NSLog(#"Alert Permission Granted");
Basically, it just dont work. I get "Alert Permission Granted" when the allow notification switch is clearly set to off in app settings. If i switch it to on, the settings dont change either. Below is the console output for grantedSettings. It stays the same. I have other cases where something is off. For now I am resorting to just removing code. I had to do this in the first place in case a user accidentally pressed cancel on the initial prompt (and yet requests alerts in-app).
granted settings: <UIUserNotificationSettings: 0x17042e940; types: (UIUserNotificationTypeAlert UIUserNotificationTypeBadge UIUserNotificationTypeSound);>
Any insight in this buggy area? Btw, I am running on 8.1. The need for this is not entirely the same on ios9, as ios9 will let the user be prompted for notification permission more than once pr device..
I used the below method in one of my project to determine whether the user has given permission or not, or whether he/she actually turned off the notifications in settings. Put this method in Appdelegate and check
-(BOOL)notificationServicesEnabled {
BOOL isEnabled = NO;
if ([[UIApplication sharedApplication] respondsToSelector:#selector(currentUserNotificationSettings)]){
UIUserNotificationSettings *notificationSettings = [[UIApplication sharedApplication] currentUserNotificationSettings];
if (!notificationSettings || (notificationSettings.types == UIUserNotificationTypeNone)) {
isEnabled = NO;
} else {
isEnabled = YES;
}
} else {
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types & UIRemoteNotificationTypeAlert) {
isEnabled = YES;
} else{
isEnabled = NO;
}
}
return isEnabled;
}
Then you can simple check with condition
if([self notificationServicesEnabled])
I hope this should help you out.
In iOS 9, to check whether the app is currently registered for remote notifications, use this:
BOOL isEnabled = [[UIApplication sharedApplication] isRegisteredForRemoteNotifications];
I am trying to update some old code to get it to work in IOS 8. I have read through
Location Services not working in iOS 8
but I am still very confused as to how to correctly implement the methodology.
I have added in
<key>NSLocationWhenInUseUsageDescription</key>
<string>The spirit of stack overflow is coders helping coders</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>I have learned more on stack overflow than anything else</string>
into the infoPlist.strings
but I am not sure how to update my code to get it to execute properly. Here is a copy of the old code that I am using. Can anyone provide insight on how to properly update this code in order to get it to work with IOS 8?
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
NSLog(#"%s", __PRETTY_FUNCTION__);
switch (status) {
case kCLAuthorizationStatusAuthorizedAlways:
{
NSLog(#"kCLAuthorizationStatusAuthorized");
// Re-enable the post button if it was disabled before.
self.navigationItem.rightBarButtonItem.enabled = YES;
[self.locationManager startUpdatingLocation];
}
break;
case kCLAuthorizationStatusDenied:
NSLog(#"kCLAuthorizationStatusDenied");
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Anywall can’t access your current location.\n\nTo view nearby posts or create a post at your current location, turn on access for Anywall to your location in the Settings app under Location Services." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
// Disable the post button.
self.navigationItem.rightBarButtonItem.enabled = NO;
}
break;
case kCLAuthorizationStatusNotDetermined:
{
NSLog(#"kCLAuthorizationStatusNotDetermined");
}
break;
case kCLAuthorizationStatusRestricted:
{
NSLog(#"kCLAuthorizationStatusRestricted");
}
break;
}
}
The code I am using here is from an old version of parse's Anywall Tutorial. I have tried adding in
case kCLAuthorizationStatusNotDetermined:
{
NSLog(#"kCLAuthorizationStatusNotDetermined");
[self.locationManager requestAlwaysAuthorization];
}
break;
In addition the application also displays the user's location on a map do I have to update that method as well?
You have to do it like this:
1)#import <CoreLocation/CoreLocation.h>
2)Set delegate CLLocationManagerDelegate
3)Create CLLocationManager *locationManager; Object
4)#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) in your .m file
5)Setup location manager
if (self.locationManager==nil) {
self.locationManager = [[CLLocationManager alloc]init];
}
self.locationManager.delegate = self;
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
// If the status is denied or only granted for when in use, display an alert
if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) {
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"8.0"))
{
NSString *title;
title = (status == kCLAuthorizationStatusDenied) ? #"Location services are off" : #"Background location is not enabled";
NSString *message = #"To use background location you must turn on 'Always' in the Location Services Settings";
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Settings", nil];
[alertView setTag:1001];
[alertView show];
[alertView release];
}
else{
NSString *titles;
titles = #"Title";
NSString *msg = #"Location services are off. To use location services you must turn on 'Always' in the Location Services Settings from Click on 'Settings' > 'Privacy' > 'Location Services'. Enable the 'Location Services' ('ON')";
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:titles
message:msg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}
// The user has not enabled any location services. Request background authorization.
else if (status == kCLAuthorizationStatusNotDetermined) {
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"8.0"))
{
[self.locationManager requestAlwaysAuthorization];
}
}
[self.locationManager startUpdatingLocation];
6)Setup alert view for iOS 8
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (alertView.tag==1001){
if (buttonIndex == 1) {
// Send the user to the Settings for this app
NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
[[UIApplication sharedApplication] openURL:settingsURL];
}
}
}
I have the following code that I use for push notifications:
located within my appdelegate.m is the following code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
//Register to receive notifcations
//-- Set Notification
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
}
[Pushbots getInstance];
NSDictionary * userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if(userInfo) {
// Notification Message
NSString* notificationMsg = [userInfo valueForKey:#"message"];
// Custom Field
NSString* title = [userInfo valueForKey:#"title"];
NSLog(#"Notification Msg is %# and Custom field title = %#", notificationMsg , title);
}
return YES;
}
-(void)onReceivePushNotification:(NSDictionary *) pushDict andPayload:(NSDictionary *)payload {
[payload valueForKey:#"title"];
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"New Alert !" message:[pushDict valueForKey:#"alert"] delegate:self cancelButtonTitle:#"Thanks !" otherButtonTitles: #"Open",nil];
[message show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Open"]) {
[[Pushbots getInstance] OpenedNotification];
// set Badge to 0
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
// reset badge on the server
[[Pushbots getInstance] resetBadgeCount];
}
}
This code works fine when the application is not closed, it presents me with the notification alert view.
HOWEVER it does not work properly when the application is closed fully and not running in background.
And I dont know what to do about it!
Thanks in advance?
you cannot since displaying an alert view required the notification invoking some part of your code, however the entry point for your code i.e. where you may first handle anything regarding your notification is on
(BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary) launchOptions
which means your app has to be awake in order to show a custom alert view.
For now you will have to settle to the default implementation ios gives you, that is the notification bar at the top.
hope ts useful
I am working with UILocalNotification to notify users about their schedule. Everything is working fine but I'd like to know whether there is a way to display notification alert on notification center when the app is in foreground.
The alert will not be fire on running application main view.
Please help me.
Put this code in didReceiveRemoteNotification Method.
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive)
{
NSString *cancelTitle = #"OK";
NSString *message = [[userInfo valueForKey:#"aps"] valueForKey:#"alert"];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Test"
message:message
delegate:self
cancelButtonTitle:cancelTitle
otherButtonTitles:nil, nil];
[alertView show];
} else
{
//Do stuff that you would do if the application was not active
}