Skip to content

Commit

Permalink
Merge pull request #1451 from OneSignal/fix/clearing_notifs_when_swip…
Browse files Browse the repository at this point in the history
…ing_notif_center

Fix clearing notifications when the application becomes active instead of when it enters foreground
  • Loading branch information
emawby authored Jun 27, 2024
2 parents f0552dd + bb60c99 commit f1489cc
Show file tree
Hide file tree
Showing 12 changed files with 560 additions and 19 deletions.
289 changes: 288 additions & 1 deletion iOS_SDK/OneSignalSDK/OneSignal.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,20 @@
ReferencedContainer = "container:OneSignal.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "DEBA2A192C20E35E00E234DB"
BuildableName = "OneSignalNotificationsTests.xctest"
BlueprintName = "OneSignalNotificationsTests"
ReferencedContainer = "container:OneSignal.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
Expand Down Expand Up @@ -121,6 +135,13 @@
BlueprintName = "OneSignalCoreTests"
ReferencedContainer = "container:OneSignal.xcodeproj">
</BuildableReference>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "DEBA2A192C20E35E00E234DB"
BuildableName = "OneSignalNotificationsTests.xctest"
BlueprintName = "OneSignalNotificationsTests"
ReferencedContainer = "container:OneSignal.xcodeproj">
</BuildableReference>
</CodeCoverageTargets>
<Testables>
<TestableReference
Expand Down Expand Up @@ -163,6 +184,16 @@
ReferencedContainer = "container:OneSignal.xcodeproj">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "DEBA2A192C20E35E00E234DB"
BuildableName = "OneSignalNotificationsTests.xctest"
BlueprintName = "OneSignalNotificationsTests"
ReferencedContainer = "container:OneSignal.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
Expand Down
25 changes: 25 additions & 0 deletions iOS_SDK/OneSignalSDK/OneSignalCore/Source/OSBundleUtils.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
Modified MIT License
Copyright 2024 OneSignal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
2. All copies of substantial portions of the Software may only be used in connection
with services provided by OneSignal.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

@interface OSBundleUtils : NSObject
+ (BOOL)isAppUsingUIScene;
@end
34 changes: 34 additions & 0 deletions iOS_SDK/OneSignalSDK/OneSignalCore/Source/OSBundleUtils.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
Modified MIT License
Copyright 2024 OneSignal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
2. All copies of substantial portions of the Software may only be used in connection
with services provided by OneSignal.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#import <Foundation/Foundation.h>
#import "OSBundleUtils.h"
@implementation OSBundleUtils

+ (BOOL)isAppUsingUIScene {
if (@available(iOS 13.0, *)) {
return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIApplicationSceneManifest"] != nil;
}
return NO;
}

@end
2 changes: 1 addition & 1 deletion iOS_SDK/OneSignalSDK/OneSignalCore/Source/OneSignalCore.h
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
#import <OneSignalCore/OneSignalWrapper.h>
#import <OneSignalCore/OSInAppMessages.h>
#import <OneSignalCore/OSLocation.h>

#import <OneSignalCore/OSBundleUtils.h>
// TODO: Testing: Should this class be defined in this file?
@interface OneSignalCoreImpl : NSObject

Expand Down
44 changes: 44 additions & 0 deletions iOS_SDK/OneSignalSDK/OneSignalCoreMocks/OneSignalCoreMocks.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,48 @@ public class OneSignalCoreMocks: NSObject {
let expectation = XCTestExpectation(description: "Wait for \(seconds) seconds")
_ = XCTWaiter.wait(for: [expectation], timeout: seconds)
}

@objc public static func backgroundApp() {
if (OSBundleUtils.isAppUsingUIScene()) {
if #available(iOS 13.0, *) {
NotificationCenter.default.post(name: UIScene.willDeactivateNotification, object: nil)
NotificationCenter.default.post(name: UIScene.didEnterBackgroundNotification, object: nil)
}
} else {
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.post(name: UIApplication.didEnterBackgroundNotification, object: nil)
}
}

@objc public static func foregroundApp() {
if (OSBundleUtils.isAppUsingUIScene()) {
if #available(iOS 13.0, *) {
NotificationCenter.default.post(name: UIScene.willEnterForegroundNotification, object: nil)
NotificationCenter.default.post(name: UIScene.didActivateNotification, object: nil)
}
} else {
NotificationCenter.default.post(name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
}
}

@objc public static func resignActive() {
if (OSBundleUtils.isAppUsingUIScene()) {
if #available(iOS 13.0, *) {
NotificationCenter.default.post(name: UIScene.willDeactivateNotification, object: nil)
}
} else {
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
}
}

@objc public static func becomeActive() {
if (OSBundleUtils.isAppUsingUIScene()) {
if #available(iOS 13.0, *) {
NotificationCenter.default.post(name: UIScene.didActivateNotification, object: nil)
}
} else {
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -251,9 +251,38 @@ + (void)start {
@selector(onesignalSetApplicationIconBadgeNumber:)
);
[OneSignalNotificationsUNUserNotificationCenter setup];

[self registerLifecycleObserver];

}
#pragma clang diagnostic pop

+ (void)registerLifecycleObserver {
// Replacing swizzled lifecycle selectors with notification center observers for scene based Apps
if ([OSBundleUtils isAppUsingUIScene]) {
[self registerLifecycleObserverAsUIScene];
} else {
[self registerLifecycleObserverAsUIApplication];
}
}

+ (void)registerLifecycleObserverAsUIScene {
if (@available(iOS 13.0, *)) {
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"OSNotificationManager registering for Scene Lifecycle notifications"];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground) name:@"UISceneWillEnterForegroundNotification" object:nil];
}
}

+ (void)registerLifecycleObserverAsUIApplication {
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"OSNotificationManager registering for Application Lifecycle notifications"];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
}

+ (void)willEnterForeground {
[OSNotificationsManager clearBadgeCount:false fromClearAll:false];
[OSNotificationsManager sendNotificationTypesUpdateToDelegate];
}

+ (void)resetLocals {
_lastMessageReceived = nil;
_lastMessageIdFromAction = nil;
Expand Down Expand Up @@ -967,6 +996,10 @@ + (UNNotificationRequest*)prepareUNNotificationRequest:(OSNotification*)notifica
return [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
}

- (void)dealloc {
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"OSNotificationsManager observer deallocated"];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
Modified MIT License
Copyright 2024 OneSignal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
2. All copies of substantial portions of the Software may only be used in connection
with services provided by OneSignal.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

import XCTest
import OneSignalNotifications
import OneSignalCoreMocks
import UIKit

final class OneSignalNotificationsTests: XCTestCase {

var notifTypes: Int32 = 0
var token: String = ""

override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
self.notifTypes = 0
self.token = ""
}

override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}

func testClearBadgesWhenAppEntersForeground() throws {
// NotificationManager Start to register lifecycle listener
OSNotificationsManager.start()
// Set badge count > 0
UIApplication.shared.applicationIconBadgeNumber = 1
// Then background the app
OneSignalCoreMocks.backgroundApp()
// Foreground the app
OneSignalCoreMocks.foregroundApp()
// Ensure that badge count == 0
XCTAssertEqual(UIApplication.shared.applicationIconBadgeNumber, 0)
}

func testDontclearBadgesWhenAppBecomesActive() throws {
// NotificationManager Start to register lifecycle listener
OSNotificationsManager.start()
// Set badge count > 0
UIApplication.shared.applicationIconBadgeNumber = 1
// Then resign active
OneSignalCoreMocks.resignActive()
// App becomes active the app
OneSignalCoreMocks.becomeActive()
// Ensure that badge count == 1
XCTAssertEqual(UIApplication.shared.applicationIconBadgeNumber, 1)
}

func testUpdateNotificationTypesOnAppEntersForeground() throws {
// NotificationManager Start to register lifecycle listener
OSNotificationsManager.start()

OSNotificationsManager.delegate = self

XCTAssertEqual(self.notifTypes, 0)

// Then background the app
OneSignalCoreMocks.backgroundApp()

// Foreground the app for within 30 seconds
OneSignalCoreMocks.foregroundApp()

// Ensure that the delegate is updated with the new notification type
XCTAssertEqual(self.notifTypes, ERROR_PUSH_NEVER_PROMPTED)
}


}

extension OneSignalNotificationsTests: OneSignalNotificationsDelegate {
public func setNotificationTypes(_ notificationTypes: Int32) {
self.notifTypes = notificationTypes
}

public func setPushToken(_ pushToken: String) {
self.token = pushToken
}
}
2 changes: 1 addition & 1 deletion iOS_SDK/OneSignalSDK/Source/OneSignalLifecycleObserver.m
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ +(OneSignalLifecycleObserver*) sharedInstance {

+ (void)registerLifecycleObserver {
// Replacing swizzled lifecycle selectors with notification center observers for scene based Apps
if ([UIApplication isAppUsingUIScene]) {
if ([OSBundleUtils isAppUsingUIScene]) {
[self registerLifecycleObserverAsUIScene];
} else {
[self registerLifecycleObserverAsUIApplication];
Expand Down
10 changes: 3 additions & 7 deletions iOS_SDK/OneSignalSDK/Source/OneSignalTracker.m
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,12 @@ + (void)onFocus:(BOOL)toBackground {
if (toBackground) {
[self applicationBackgrounded];
} else {
[self applicationForegrounded];
[self applicationBecameActive];
}
}

+ (void)applicationForegrounded {
[OneSignalLog onesignalLog:ONE_S_LL_DEBUG message:@"Application Foregrounded started"];
+ (void)applicationBecameActive {
[OneSignalLog onesignalLog:ONE_S_LL_DEBUG message:@"Application Active started"];
[OSFocusTimeProcessorFactory cancelFocusCall];

if (OSSessionManager.sharedSessionManager.appEntryState != NOTIFICATION_CLICK)
Expand All @@ -94,14 +94,10 @@ + (void)applicationForegrounded {
if ([OneSignal shouldStartNewSession])
[OneSignal startNewSession:NO];
else {
// This checks if notification permissions changed when app was backgrounded
[OSNotificationsManager sendNotificationTypesUpdateToDelegate];
[[OSSessionManager sharedSessionManager] attemptSessionUpgrade];
// TODO: Here it used to call receivedInAppMessageJson with nil, this method no longer exists
// [OneSignal receivedInAppMessageJson:nil];
}

[OSNotificationsManager clearBadgeCount:false fromClearAll:false];
}

+ (void)applicationBackgrounded {
Expand Down
1 change: 0 additions & 1 deletion iOS_SDK/OneSignalSDK/Source/UIApplication+OneSignal.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,4 @@
#import <UIKit/UIKit.h>
@interface UIApplication (OneSignal)
+ (BOOL)applicationIsActive;
+ (BOOL)isAppUsingUIScene;
@end
10 changes: 2 additions & 8 deletions iOS_SDK/OneSignalSDK/Source/UIApplication+OneSignal.m
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,12 @@

#import "UIApplication+OneSignal.h"
#import <OneSignalCore/OneSignalCommonDefines.h>
#import <OneSignalCore/OSBundleUtils.h>

@implementation UIApplication (OneSignal)

+ (BOOL)applicationIsActive {
if ([self isAppUsingUIScene] && [NSThread isMainThread]) {
if ([OSBundleUtils isAppUsingUIScene] && [NSThread isMainThread]) {
if (@available(iOS 13.0, *)) {
UIWindow *keyWindow = UIApplication.sharedApplication.keyWindow;
id windowScene = [keyWindow performSelector:@selector(windowScene)];
Expand All @@ -43,11 +44,4 @@ + (BOOL)applicationIsActive {
return [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
}

+ (BOOL)isAppUsingUIScene {
if (@available(iOS 13.0, *)) {
return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIApplicationSceneManifest"] != nil;
}
return NO;
}

@end

0 comments on commit f1489cc

Please sign in to comment.