[iOS]判斷PushNotification是否開啟

Push Notification
  • 有時候需要判斷Notification是否開啟,iOS提供以下Type可以判斷
typedef NS_OPTIONS(NSUInteger, UIUserNotificationType) {
UIUserNotificationTypeNone = 0, // the application may not present any UI upon a notification being received
UIUserNotificationTypeBadge = 1 << 0, // the application may badge its icon upon a notification being received
UIUserNotificationTypeSound = 1 << 1, // the application may play a sound upon a notification being received
UIUserNotificationTypeAlert = 1 << 2, // the application may display an alert upon a notification being received
}
  • 只檢查是否開啟
if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]) {
// iOS8+
UIUserNotificationType types = [[[UIApplication sharedApplication] currentUserNotificationSettings] types];
if (types == UIUserNotificationTypeNone){
// 未開啟通知
}
else{
// 開啟通知
}
}
else {
// iOS7-
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types == UIUserNotificationTypeNone){
// 未開啟通知
}
else{
// 開啟通知
}
}
  • 針對每項Type去偵測(Alert、Sound、Badge)
BOOL isAlertOn;
BOOL isSoundOn;
BOOL isBadgeOn;
if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]) {
// iOS8+
UIUserNotificationType types = [[[UIApplication sharedApplication] currentUserNotificationSettings] types];
isAlertOn = (types & UIUserNotificationTypeAlert);
isSoundOn = (types & UIUserNotificationTypeSound);
isBadgeOn = (types & UIUserNotificationTypeBadge);
}
else {
// iOS7-
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
isAlertOn = (types & UIRemoteNotificationTypeAlert);
isSoundOn = (types & UIRemoteNotificationTypeSound);
isBadgeOn = (types & UIRemoteNotificationTypeBadge);
}
if (!isAlertOn && !isSoundOn && !isBadgeOn) {
// 未開啟通知
}
else{
// 有開啟通知
if (isAlertOn) {
// 顯示於通知中心
}
if (isSoundOn) {
// 聲音
}
if (isBadgeOn) {
// APP包含標記圖像
}
}
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.