Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Notification receipt with silent push #391

Open
wants to merge 58 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
4ae7963
test
york-wei Feb 20, 2024
27d6015
add notif for test
york-wei Feb 21, 2024
1380daf
Update Radar.m
york-wei Feb 23, 2024
c237b40
call startTracking continuous only
york-wei Mar 6, 2024
bc7cde6
save token to settings and send up in track
corypisano May 31, 2024
84d1901
handle actions array in silent push payload
corypisano May 31, 2024
1dd8a1f
save for branch switch
KennyHuRadar Aug 15, 2024
6930308
Merge branch 'master' into swizzling-unnotification-center
KennyHuRadar Aug 16, 2024
cbce1a7
skip swizzling for tests
KennyHuRadar Aug 16, 2024
564138b
use different type for each kind of opening notification
KennyHuRadar Aug 19, 2024
8c0d25c
save for eod
KennyHuRadar Aug 20, 2024
a5ac78f
eod-ish save
KennyHuRadar Aug 20, 2024
4f48ed7
run only notification center checks on device and not tests
KennyHuRadar Aug 20, 2024
a7d3039
make the callback nullable
KennyHuRadar Aug 20, 2024
d1ada93
modularize notification delivery detetection logic and also refactor
KennyHuRadar Aug 21, 2024
07287a3
implement background processing and cleanup
KennyHuRadar Aug 21, 2024
688fddb
clean up
KennyHuRadar Aug 21, 2024
6052111
version restrict background processing
KennyHuRadar Aug 21, 2024
143f105
clean up
KennyHuRadar Aug 21, 2024
ebbcfd4
clean up
KennyHuRadar Aug 21, 2024
225f917
clean up
KennyHuRadar Aug 23, 2024
6fbefc0
resolve merge conflict
KennyHuRadar Aug 26, 2024
17606a9
move swizzle out of init
KennyHuRadar Aug 26, 2024
9163718
add swift name
KennyHuRadar Aug 26, 2024
41b9c0e
change init of background jobs
KennyHuRadar Aug 26, 2024
6256006
move swizzling back into init
KennyHuRadar Aug 26, 2024
ee95354
do not add notifications if we do not have permissions
KennyHuRadar Aug 26, 2024
6b89e9c
change name to native setup
KennyHuRadar Aug 26, 2024
5985f0e
log all app opens for now
KennyHuRadar Aug 26, 2024
a9154aa
add info to metadata
KennyHuRadar Aug 26, 2024
dd2d1a8
change to metadata fields
KennyHuRadar Aug 27, 2024
e3dd770
change name to conversionSource
KennyHuRadar Aug 27, 2024
7edff55
change casing
KennyHuRadar Aug 27, 2024
14e879b
only log either notification open or normal app open
KennyHuRadar Aug 27, 2024
f287a75
do nothing for the method notification
KennyHuRadar Aug 27, 2024
65a31ad
formatting
KennyHuRadar Aug 27, 2024
07b120b
remove dead comment
KennyHuRadar Aug 27, 2024
28ea860
Merge branch 'master' into swizzling-unnotification-center
KennyHuRadar Aug 28, 2024
51e80cb
remember notification permission into radar state
KennyHuRadar Aug 29, 2024
fab81f6
change logging level
KennyHuRadar Aug 29, 2024
1b20ad1
move the call so that it does not perform in test env
KennyHuRadar Aug 29, 2024
d6dfc1a
temp adding webhook pings to bg tasks so we have a better idea on whe…
KennyHuRadar Sep 4, 2024
5c9ff70
changes and fixes, server side working
KennyHuRadar Sep 4, 2024
ad9bbba
add more logging
KennyHuRadar Sep 4, 2024
fab123a
fix potential race condition
KennyHuRadar Sep 4, 2024
eb46559
remove clearing of pending notifications when the app foregrounds
KennyHuRadar Sep 4, 2024
7a851f3
Merge branch 'master' into silent-push-spike
KennyHuRadar Sep 5, 2024
2724535
merging in silent push piece
KennyHuRadar Sep 5, 2024
6513b52
save for branch switch
KennyHuRadar Sep 5, 2024
a007017
save for branch switch
KennyHuRadar Sep 6, 2024
d9756c7
save for branch switch
KennyHuRadar Sep 9, 2024
c4b8a47
save for branch switch
KennyHuRadar Sep 12, 2024
f55721b
save for branch switch
KennyHuRadar Sep 13, 2024
46df72e
rough draft
KennyHuRadar Sep 16, 2024
6a916d7
Merge branch 'master' into notification-recipt-with-silent-push
KennyHuRadar Sep 16, 2024
6079167
fix merge
KennyHuRadar Sep 16, 2024
63ceea3
remove background job code
KennyHuRadar Sep 16, 2024
11b0af1
remove dead code
KennyHuRadar Sep 16, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions Example/Example.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
DD86FD0B23918B3C003225F6 /* Example-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Example-Bridging-Header.h"; sourceTree = "<group>"; };
DDB861D22385FC3E00770661 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = "<group>"; };
E698B7382C626AE600084371 /* RadarSDKMotion.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RadarSDKMotion.xcodeproj; path = ../../RadarSDKMotion/RadarSDKMotion.xcodeproj; sourceTree = "<group>"; };
E6E29C3B2C8B6B5A000A6690 /* Example.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Example.entitlements; sourceTree = "<group>"; };
F625D7F82C3337650024D1E7 /* Launch Screen.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = "Launch Screen.storyboard"; sourceTree = "<group>"; };
/* End PBXFileReference section */

Expand Down Expand Up @@ -110,6 +111,7 @@
DD236D25230A006700EB88F9 /* Example */ = {
isa = PBXGroup;
children = (
E6E29C3B2C8B6B5A000A6690 /* Example.entitlements */,
DD86FD0B23918B3C003225F6 /* Example-Bridging-Header.h */,
DD236D34230A006900EB88F9 /* Info.plist */,
DDB861D22385FC3E00770661 /* Default-568h@2x.png */,
Expand Down Expand Up @@ -393,6 +395,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = Example/Example.entitlements;
CODE_SIGN_IDENTITY = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = 96GHH65B9D;
Expand All @@ -410,7 +413,7 @@
"@executable_path/Frameworks",
);
MARKETING_VERSION = 3.5.0;
PRODUCT_BUNDLE_IDENTIFIER = io.radar.example;
PRODUCT_BUNDLE_IDENTIFIER = io.radar.iosexample;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_VERSION = 5.0;
Expand All @@ -422,6 +425,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = Example/Example.entitlements;
CODE_SIGN_IDENTITY = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = 96GHH65B9D;
Expand All @@ -439,7 +443,7 @@
"@executable_path/Frameworks",
);
MARKETING_VERSION = 3.5.0;
PRODUCT_BUNDLE_IDENTIFIER = io.radar.example;
PRODUCT_BUNDLE_IDENTIFIER = io.radar.iosexample;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_VERSION = 5.0;
Expand Down
29 changes: 23 additions & 6 deletions Example/Example/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,25 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UIWindowSceneDelegate, UN
Radar.setMetadata([ "foo": "bar" ])
Radar.setDelegate(self)
Radar.setVerifiedDelegate(self)

UIApplication.shared.registerForRemoteNotifications()
return true
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
NSLog("Successfully registered for remote notifications with device token: \(deviceToken)")
Radar.handleDeviceToken(forRemoteNotifications: deviceToken)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NSLog("Failed to register for remote notifications: \(error)")
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
NSLog("didReceiveRemoteNotification with userInfo: %@", userInfo)
Radar.handleSilentPush(payload: userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}

func demoButton(text: String, function: @escaping () -> Void) {
guard let scrollView = self.scrollView else { return }

Expand Down Expand Up @@ -284,6 +299,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UIWindowSceneDelegate, UN
function()
}
}

demoButton(text: "create dummy notifications") {Radar.testNotificationChecker()}
}

func requestLocationPermissions() {
Expand Down Expand Up @@ -344,24 +361,24 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UIWindowSceneDelegate, UN

func didUpdateLocation(_ location: CLLocation, user: RadarUser) {
let body = "\(user.stopped ? "Stopped at" : "Moved to") location (\(location.coordinate.latitude), \(location.coordinate.longitude)) with accuracy \(location.horizontalAccuracy) meters"
self.notify(body)
//self.notify(body)
}

func didUpdateClientLocation(_ location: CLLocation, stopped: Bool, source: RadarLocationSource) {
let body = "\(stopped ? "Client stopped at" : "Client moved to") location (\(location.coordinate.latitude), \(location.coordinate.longitude)) with accuracy \(location.horizontalAccuracy) meters and source \(Utils.stringForRadarLocationSource(source))"
self.notify(body)
//self.notify(body)
}

func didFail(status: RadarStatus) {
self.notify(Radar.stringForStatus(status))
//self.notify(Radar.stringForStatus(status))
}

func didLog(message: String) {
self.notify(message)
//self.notify(message)
}

func didUpdateToken(_ token: RadarVerifiedLocationToken) {

}

}
8 changes: 8 additions & 0 deletions Example/Example/Example.entitlements
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>development</string>
</dict>
</plist>
4 changes: 4 additions & 0 deletions Example/Example/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array/>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
Expand Down Expand Up @@ -71,6 +73,8 @@
<array>
<string>fetch</string>
<string>location</string>
<string>processing</string>
<string>remote-notification</string>
</array>
<key>UILaunchStoryboardName</key>
<string>Launch Screen.storyboard</string>
Expand Down
6 changes: 6 additions & 0 deletions RadarSDK/Include/Radar.h
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,8 @@ typedef void (^_Nullable RadarLogConversionCompletionHandler)(RadarStatus status
*/
+ (void)setAnonymousTrackingEnabled:(BOOL)enabled;

+ (void)handleDeviceTokenForRemoteNotifications:(NSData *)deviceToken;

#pragma mark - Location

/**
Expand Down Expand Up @@ -590,6 +592,8 @@ typedef void (^_Nullable RadarLogConversionCompletionHandler)(RadarStatus status
*/
+ (BOOL)isUsingRemoteTrackingOptions;

+ (void)handleSilentPushWithPayload:(NSDictionary *)payload NS_SWIFT_NAME(handleSilentPush(payload:));

#pragma mark - Delegate

/**
Expand Down Expand Up @@ -1232,6 +1236,8 @@ typedef void (^_Nullable RadarLogConversionCompletionHandler)(RadarStatus status
*/
+ (void)nativeSetup NS_SWIFT_NAME(nativeSetup());

+ (void) testNotificationChecker NS_SWIFT_NAME(testNotificationChecker());

@end

NS_ASSUME_NONNULL_END
63 changes: 61 additions & 2 deletions RadarSDK/Radar.m
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,20 @@ + (void)initializeWithPublishableKey:(NSString *)publishableKey options:(RadarIn
name:UIApplicationWillEnterForegroundNotification
object:nil];

[[NSNotificationCenter defaultCenter] addObserver:[self sharedInstance]
selector:@selector(applicationDidEnterBackground)
name:UIApplicationDidEnterBackgroundNotification
object:nil];

[RadarSettings setPublishableKey:publishableKey];

RadarSdkConfiguration *sdkConfiguration = [RadarSettings sdkConfiguration];


if (NSClassFromString(@"XCTestCase") == nil && options.autoLogNotificationConversions) {
[Radar nativeSetup];
if (options.autoLogNotificationConversions) {
[Radar nativeSetup];
}
}

if (sdkConfiguration.usePersistence) {
Expand Down Expand Up @@ -146,6 +154,21 @@ + (void)setAnonymousTrackingEnabled:(BOOL)enabled {
[RadarSettings setAnonymousTrackingEnabled:enabled];
}

+ (void)handleDeviceTokenForRemoteNotifications:(NSData *)deviceToken {
[[RadarLogger sharedInstance] logWithLevel:RadarLogLevelDebug message:@"Received device token for remote notifications."];

const char *data = (char *)[deviceToken bytes];
NSMutableString *token = [NSMutableString string];
for (NSUInteger i = 0; i < [deviceToken length]; i++) {
[token appendFormat:@"%02.2hhX", data[i]];
}
//print the token
NSLog(@"deviceToken: %@", token);

// Save to settings
[RadarSettings setDevicePushToken:token];
}

#pragma mark - Location

+ (void)getLocationWithCompletionHandler:(RadarLocationCompletionHandler)completionHandler {
Expand Down Expand Up @@ -420,6 +443,32 @@ + (BOOL)isUsingRemoteTrackingOptions {
return [RadarSettings remoteTrackingOptions] != nil;
}

+ (void)handleSilentPushWithPayload:(NSDictionary *)payload {
NSString *message = [NSString stringWithFormat:@"App received silent push notification | payload=%@", payload];
[[RadarLogger sharedInstance] logWithLevel:RadarLogLevelDebug type:RadarLogTypeNone message:message includeDate:YES includeBattery:YES];


[RadarNotificationHelper showDidReceiveSilentPushNotification:payload];

// [RadarNotificationHelper checkForSentOnPremiseNotifications:^{}];

// payload contains array of actions, only using a single action for now
// action is a dictionary with type and optional data
// if (payload[@"actions"]) {
// NSDictionary *action = payload[@"actions"][0];

// [[RadarLogger sharedInstance] logWithLevel:RadarLogLevelDebug type:RadarLogTypeNone message:message includeDate:YES includeBattery:YES];

// // TRACK_ONCE
// if ([action[@"type"] isEqualToString:@"TRACK_ONCE"]) {
// [Radar trackOnceWithCompletionHandler:^(RadarStatus status, CLLocation * _Nullable location, NSArray<RadarEvent *> * _Nullable events, RadarUser * _Nullable user) {
// }];
// }
// // START_TRACKING
// // ...
// }
}

#pragma mark - Delegate

+ (void)setDelegate:(id<RadarDelegate>)delegate {
Expand Down Expand Up @@ -1340,13 +1389,18 @@ - (void)applicationWillEnterForeground {
}

[Radar logOpenedAppConversion];

[RadarNotificationHelper checkForSentOnPremiseNotifications:^{}];

RadarSdkConfiguration *sdkConfiguration = [RadarSettings sdkConfiguration];
if (sdkConfiguration.trackOnceOnAppOpen) {
[Radar trackOnceWithCompletionHandler:nil];
}
}

- (void)applicationDidEnterBackground {

}

- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Expand Down Expand Up @@ -1388,4 +1442,9 @@ + (void)flushLogs {
}];
}

+ (void)testNotificationChecker {
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"test" content:[UNNotificationContent new] trigger:nil];
[RadarState addPendingNotificationRequest:request];
}

@end
1 change: 1 addition & 0 deletions RadarSDK/RadarAPIClient.m
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ - (void)trackWithLocation:(CLLocation *_Nonnull)location
params[@"userId"] = [RadarSettings userId];
params[@"deviceId"] = [RadarUtils deviceId];
params[@"description"] = [RadarSettings __description];
params[@"devicePushToken"] = [RadarSettings devicePushToken];
params[@"metadata"] = [RadarSettings metadata];
NSString *sessionId = [RadarSettings sessionId];
if (sessionId) {
Expand Down
17 changes: 13 additions & 4 deletions RadarSDK/RadarLocationManager.m
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,12 @@ - (void)replaceSyncedGeofences:(NSArray<RadarGeofence *> *)geofences {
for (int i = 0; i < numGeofences; i++) {
RadarGeofence *geofence = [geofences objectAtIndex:i];
NSString *geofenceId = geofence._id;
NSString *identifier = [NSString stringWithFormat:@"%@%@", kSyncGeofenceIdentifierPrefix, geofenceId];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *timestamp = [dateFormatter stringFromDate:[NSDate date]];
NSString *identifier = [NSString stringWithFormat:@"%@%@_%@", kSyncGeofenceIdentifierPrefix, geofenceId, timestamp];

RadarCoordinate *center;
double radius = 100;
if ([geofence.geometry isKindOfClass:[RadarCircleGeometry class]]) {
Expand Down Expand Up @@ -574,7 +579,7 @@ - (void)replaceSyncedGeofences:(NSArray<RadarGeofence *> *)geofences {
} else {
[[RadarLogger sharedInstance] logWithLevel:RadarLogLevelDebug message:@"Notification does not repeat"];
}

UNLocationNotificationTrigger *trigger = [UNLocationNotificationTrigger triggerWithRegion:region repeats:repeats];

UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
Expand All @@ -586,8 +591,12 @@ - (void)replaceSyncedGeofences:(NSArray<RadarGeofence *> *)geofences {
}
}

[RadarNotificationHelper removePendingNotificationsWithCompletionHandler: ^{
[RadarNotificationHelper addOnPremiseNotificationRequests:requests];
[RadarNotificationHelper checkForSentOnPremiseNotifications: ^{
[RadarState clearPendingNotificationRequests];

[RadarNotificationHelper removePendingNotificationsWithCompletionHandler: ^{
[RadarNotificationHelper addOnPremiseNotificationRequests:requests];
}];
}];
}

Expand Down
4 changes: 4 additions & 0 deletions RadarSDK/RadarNotificationHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ typedef void (^NotificationPermissionCheckCompletion)(BOOL granted);

+ (void)showNotificationsForEvents:(NSArray<RadarEvent *> *)events;

+ (void)showDidReceiveSilentPushNotification:(NSDictionary *)payload;

+ (void)swizzleNotificationCenterDelegate;

+ (void)checkForSentOnPremiseNotifications:(void (^)(void))completionHandler;

+ (void)removePendingNotificationsWithCompletionHandler:(void (^)(void))completionHandler;

+ (void)addOnPremiseNotificationRequests:(NSArray<UNNotificationRequest *> *)requests;
Expand Down
Loading
Loading