Skip to content

Commit

Permalink
Merge pull request #3268 from vector-im/remove_pushkit
Browse files Browse the repository at this point in the history
Remove PushKit
  • Loading branch information
ismailgulek authored May 29, 2020
2 parents 73ab5fe + 0b639e8 commit 0d73c8d
Show file tree
Hide file tree
Showing 17 changed files with 1,108 additions and 148 deletions.
4 changes: 4 additions & 0 deletions Podfile
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ abstract_target 'RiotPods' do
import_MatrixKitAppExtension
end

target "RiotNSE" do
import_MatrixKitAppExtension
end

end


Expand Down
212 changes: 212 additions & 0 deletions Riot.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

46 changes: 38 additions & 8 deletions Riot/AppDelegate.m
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,28 @@ - (void)registerForRemoteNotificationsWithCompletion:(nullable void (^)(NSError
[self.pushNotificationService registerForRemoteNotificationsWithCompletion:completion];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[self.pushNotificationService didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];

NSString * deviceTokenString = [[[[deviceToken description]
stringByReplacingOccurrencesOfString: @"<" withString: @""]
stringByReplacingOccurrencesOfString: @">" withString: @""]
stringByReplacingOccurrencesOfString: @" " withString: @""];

NSLog(@"The generated device token string is : %@",deviceTokenString);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[self.pushNotificationService didFailToRegisterForRemoteNotificationsWithError:error];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[self.pushNotificationService didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

#pragma mark -

- (NSString*)appVersion
Expand Down Expand Up @@ -484,6 +506,9 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(
[MXSDKOptions sharedInstance].analyticsDelegate = [Analytics sharedInstance];
[DecryptionFailureTracker sharedInstance].delegate = [Analytics sharedInstance];
[[Analytics sharedInstance] start];

// Disable CallKit
[MXKAppSettings standardAppSettings].enableCallKit = NO;

self.pushNotificationService = [PushNotificationService new];
self.pushNotificationService.delegate = self;
Expand Down Expand Up @@ -1953,7 +1978,7 @@ - (void)initMatrixSessions
if (isPushRegistered)
{
// Enable push notifications by default on new added account
[account enablePushKitNotifications:YES success:nil failure:nil];
[account enablePushNotifications:YES success:nil failure:nil];
}
else
{
Expand Down Expand Up @@ -2034,13 +2059,13 @@ - (void)initMatrixSessions
accountManager.storeClass = [MXFileStore class];

// Disable APNS use.
if (accountManager.apnsDeviceToken)
{
// We use now Pushkit, unregister for all remote notifications received via Apple Push Notification service.
[[UIApplication sharedApplication] unregisterForRemoteNotifications];
[accountManager setApnsDeviceToken:nil];
}
// if (accountManager.apnsDeviceToken)
// {
// // We use now Pushkit, unregister for all remote notifications received via Apple Push Notification service.
// [[UIApplication sharedApplication] unregisterForRemoteNotifications];
// [accountManager setApnsDeviceToken:nil];
// }

// Observers have been defined, we can start a matrix session for each enabled accounts.
NSLog(@"[AppDelegate] initMatrixSessions: prepareSessionForActiveAccounts (app state: %tu)", [[UIApplication sharedApplication] applicationState]);
[accountManager prepareSessionForActiveAccounts];
Expand Down Expand Up @@ -4569,6 +4594,11 @@ - (void)setupUserDefaults
NSDictionary *defaults = [NSDictionary dictionaryWithContentsOfFile:defaultsPathFromApp];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];

if (!RiotSettings.shared.isUserDefaultsMigrated)
{
[RiotSettings.shared migrate];
}

// Now use RiotSettings and NSUserDefaults to store `showDecryptedContentInNotifications` setting option
// Migrate this information from main MXKAccount to RiotSettings, if value is not in UserDefaults

Expand Down
4 changes: 4 additions & 0 deletions Riot/Assets/Riot-Defaults.plist
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
<string>im.vector.app.ios.voip.prod</string>
<key>pushKitAppIdDev</key>
<string>im.vector.app.ios.voip.dev</string>
<key>pusherAppIdDev</key>
<string>im.vector.app.ios.dev</string>
<key>pusherAppIdProd</key>
<string>im.vector.app.ios.prod</string>
<key>identityserverurl</key>
<string>https://vector.im</string>
<key>homeserverurl</key>
Expand Down
32 changes: 32 additions & 0 deletions Riot/Categories/UNUserNotificationCenter.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
Copyright 2020 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import Foundation
import UserNotifications

@objc extension UNUserNotificationCenter {

func removeUnwantedNotifications() {
UNUserNotificationCenter.current().getDeliveredNotifications { (notifications) in
// get identifiers of notifications whose category identifiers are "TO_BE_REMOVED"
let identifiersToBeRemoved = notifications.compactMap({ $0.request.content.categoryIdentifier == Constants.toBeRemovedNotificationCategoryIdentifier ? $0.request.identifier : nil })

// remove the notifications with these id's
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: identifiersToBeRemoved)
}
}

}
2 changes: 2 additions & 0 deletions Riot/Generated/RiotDefaults.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ internal enum RiotDefaults {
internal static let pushGatewayURL: String = _document["pushGatewayURL"]
internal static let pushKitAppIdDev: String = _document["pushKitAppIdDev"]
internal static let pushKitAppIdProd: String = _document["pushKitAppIdProd"]
internal static let pusherAppIdDev: String = _document["pusherAppIdDev"]
internal static let pusherAppIdProd: String = _document["pusherAppIdProd"]
internal static let roomDirectoryServers: [String: Any] = _document["roomDirectoryServers"]
internal static let showAllEventsInRoomHistory: Bool = _document["showAllEventsInRoomHistory"]
internal static let showLeftMembersInRoomMemberList: Bool = _document["showLeftMembersInRoomMemberList"]
Expand Down
14 changes: 12 additions & 2 deletions Riot/Managers/PushNotification/PushNotificationService.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,19 @@
limitations under the License.
*/

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <PushKit/PushKit.h>
#import <UserNotifications/UserNotifications.h>

@class MXSession;
@class MXEvent;
@class MXPushRule;
@class MXKAccount;
@protocol PushNotificationServiceDelegate;

NS_ASSUME_NONNULL_BEGIN

@interface PushNotificationService : NSObject <PKPushRegistryDelegate, UNUserNotificationCenterDelegate>
@interface PushNotificationService : NSObject <UNUserNotificationCenterDelegate>

/**
Is push really registered.
Expand All @@ -48,6 +51,13 @@ NS_ASSUME_NONNULL_BEGIN
*/
- (void)registerForRemoteNotificationsWithCompletion:(nullable void (^)(NSError *))completion;

- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;

- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;

- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;

/**
Perform deregistration for remote notifications.
*/
Expand Down
123 changes: 49 additions & 74 deletions Riot/Managers/PushNotification/PushNotificationService.m
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ @interface PushNotificationService()
NSMutableDictionary <NSNumber *, MXOnNotification> *notificationListenerBlocks;
}

@property (nonatomic, strong) PKPushRegistry *pushRegistry;
//@property (nonatomic, strong) PKPushRegistry *pushRegistry;

@property (nonatomic) NSMutableDictionary <NSNumber *, NSMutableArray <NSString *> *> *incomingPushEventIds;

Expand Down Expand Up @@ -110,16 +110,56 @@ - (void)registerUserNotificationSettings

- (void)registerForRemoteNotificationsWithCompletion:(nullable void (^)(NSError *))completion
{
self.pushRegistry = [[PKPushRegistry alloc] initWithQueue:nil];
self.pushRegistry.delegate = self;
self.pushRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];

self.registrationForRemoteNotificationsCompletion = completion;

dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
}

- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
MXKAccountManager* accountManager = [MXKAccountManager sharedManager];
[accountManager setApnsDeviceToken:deviceToken];
// remove PushKit pusher if exists
if (accountManager.pushDeviceToken)
{
[accountManager setPushDeviceToken:nil withPushOptions:nil];
}
// Sanity check: Make sure the Pushkit push token is deleted
NSParameterAssert(!accountManager.isPushAvailable);
NSParameterAssert(!accountManager.pushDeviceToken);

_isPushRegistered = YES;

if (self.registrationForRemoteNotificationsCompletion)
{
self.registrationForRemoteNotificationsCompletion(nil);
self.registrationForRemoteNotificationsCompletion = nil;
}
}

- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[self clearPushNotificationToken];

if (self.registrationForRemoteNotificationsCompletion)
{
self.registrationForRemoteNotificationsCompletion(error);
self.registrationForRemoteNotificationsCompletion = nil;
}
}

- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSLog(@"[PushNotificationService][Push] didReceiveRemoteNotification: applicationState: %tu - payload: %@", [UIApplication sharedApplication].applicationState, userInfo);

completionHandler(UIBackgroundFetchResultNewData);
}

- (void)deregisterRemoteNotifications
{
self.pushRegistry = nil;
_isPushRegistered = NO;
}

Expand All @@ -131,6 +171,8 @@ - (void)applicationWillEnterForeground
[array removeAllObjects];
}
[incomingPushPayloads removeAllObjects];

[[UNUserNotificationCenter currentNotificationCenter] removeUnwantedNotifications];
}

- (void)addMatrixSession:(MXSession *)mxSession
Expand Down Expand Up @@ -259,65 +301,6 @@ - (void)handleSessionStateChangesInBackgroundFor:(MXSession *)mxSession
}
}

#pragma mark - PKPushRegistryDelegate

- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(PKPushType)type
{
NSData *token = credentials.token;

NSLog(@"[PushNotificationService][Push] didUpdatePushCredentials: Got Push token: %@. Type: %@", [MXKTools logForPushToken:token], type);

MXKAccountManager* accountManager = [MXKAccountManager sharedManager];
[accountManager setPushDeviceToken:token withPushOptions:@{@"format": @"event_id_only"}];

_isPushRegistered = YES;

if (self.registrationForRemoteNotificationsCompletion)
{
self.registrationForRemoteNotificationsCompletion(nil);
self.registrationForRemoteNotificationsCompletion = nil;
}
}

- (void)pushRegistry:(PKPushRegistry *)registry didInvalidatePushTokenForType:(PKPushType)type
{
NSLog(@"[PushNotificationService][Push] didInvalidatePushTokenForType: Type: %@", type);

[self clearPushNotificationToken];
}

- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type
{
NSLog(@"[PushNotificationService][Push] didReceiveIncomingPushWithPayload: applicationState: %tu - type: %@ - payload: %@", [UIApplication sharedApplication].applicationState, payload.type, payload.dictionaryPayload);

// Display local notifications only when the app is running in background.
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
NSLog(@"[PushNotificationService][Push] didReceiveIncomingPushWithPayload while app is in background");

// Check whether an event id is provided.
NSString *eventId = payload.dictionaryPayload[@"event_id"];
if (eventId)
{
// Add this event identifier in the pending push array for each session.
for (NSMutableArray *array in self.incomingPushEventIds.allValues)
{
[array addObject:eventId];
}

// Cache payload for further usage
incomingPushPayloads[eventId] = payload.dictionaryPayload;
}
else
{
NSLog(@"[PushNotificationService][Push] didReceiveIncomingPushWithPayload - Unexpected payload %@", payload.dictionaryPayload);
}

// Trigger a background sync to handle notifications.
[self launchBackgroundSync];
}
}

#pragma mark - UNUserNotificationCenterDelegate

// iOS 10+, see application:handleActionWithIdentifier:forLocalNotification:withResponseInfo:completionHandler:
Expand Down Expand Up @@ -373,14 +356,6 @@ - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNoti
}
}

// iOS 10+, this is called when a notification is about to display in foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
NSLog(@"[PushNotificationService][Push] willPresentNotification: applicationState: %@", @([UIApplication sharedApplication].applicationState));

completionHandler(UNNotificationPresentationOptionNone);
}

#pragma mark - Other Methods

- (void)launchBackgroundSync
Expand Down Expand Up @@ -607,7 +582,7 @@ - (NSDictionary*)notificationUserInfoForEvent:(MXEvent*)event andUserId:(NSStrin
}

// iOS 10+, does the same thing as notificationBodyForEvent:pushRule:inAccount:onComplete:, except with more features
- (void)notificationContentForEvent:(MXEvent *)event pushRule:(MXPushRule *)rule inAccount:(MXKAccount *)account onComplete:(void (^)(UNNotificationContent * _Nullable notificationContent))onComplete;
- (void)notificationContentForEvent:(MXEvent *)event pushRule:(MXPushRule *)rule inAccount:(MXKAccount *)account onComplete:(void (^)(UNNotificationContent * _Nullable notificationContent))onComplete
{
if (!event.content || !event.content.count)
{
Expand Down
Loading

0 comments on commit 0d73c8d

Please sign in to comment.