Skip to content
This repository has been archived by the owner on Sep 14, 2024. It is now read-only.

Commit

Permalink
fix(ios): make api less complex
Browse files Browse the repository at this point in the history
  • Loading branch information
gtokman committed Apr 12, 2024
1 parent 02991e7 commit eff717f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 75 deletions.
5 changes: 3 additions & 2 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import * as React from 'react';

import { StyleSheet, View, Text, Button } from 'react-native';
import push, { type AuthorizationStatus } from '@candlefinance/push';
import Push, { type AuthorizationStatus } from '@candlefinance/push';

export default function App() {
const push = React.useMemo(() => new Push(), []);
const [result, setResult] = React.useState<boolean>(false);
const [status, setStatus] =
React.useState<AuthorizationStatus>('notDetermined');
Expand Down Expand Up @@ -39,7 +40,7 @@ export default function App() {
push.removeListener('deviceTokenReceived');
push.removeListener('errorReceived');
};
}, []);
}, [push]);

return (
<View style={styles.container}>
Expand Down
92 changes: 21 additions & 71 deletions ios/Push.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public protocol Logger {
public class SharedPush: NSObject {

static var sharedInstance: SharedPush = .init()

var isObserving: Bool = false
var notificationCallbackDictionary: [String: () -> Void] = [:]
public var emitter: RCTEventEmitter?
public var logger: Logger?
Expand All @@ -34,33 +34,15 @@ final public class Push: RCTEventEmitter {
}

@objc public override func startObserving() {
NotificationCenter.default.addObserver(
self,
selector: #selector(handleRemoteNotificationReceived),
name: Notification.Name(NotificationType.notificationReceived.rawValue),
object: nil
)

NotificationCenter.default.addObserver(
self,
selector: #selector(handleRemoteNotificationsRegistered),
name: Notification.Name(NotificationType.deviceTokenReceived.rawValue),
object: nil
)

NotificationCenter.default.addObserver(
self,
selector: #selector(handleRemoteNotificationRegistrationError),
name: Notification.Name(NotificationType.errorReceived.rawValue),
object: nil
)

super.startObserving()
shared.isObserving = true
shared.logger?.track(event: "\(#function)")
}

@objc public override func stopObserving() {
super.stopObserving()
shared.isObserving = false
shared.logger?.track(event: "\(#function)")
NotificationCenter.default.removeObserver(self)
}

public override func supportedEvents() -> [String]! {
Expand Down Expand Up @@ -125,26 +107,21 @@ final public class Push: RCTEventEmitter {

extension Push {

@objc func handleRemoteNotificationReceived(_ notification: Notification) {

guard let payload = notification.userInfo?["payload"] as? [AnyHashable: Any] else {
shared.logger?.track(event: "Fatal: Payload not found. \(#function)")
return
}

guard let kind = notification.userInfo?["kind"] as? String else {
shared.logger?.track(event: "Fatal: Kind not found. \(#function)")
@objc func handleRemoteNotificationReceived(payload: [AnyHashable: Any], kind: String) {
guard shared.isObserving else {
let message = "Fatal: Not observing. \(#function). Type: \(kind)"
handleRemoteNotificationRegistrationError(error: message)
shared.logger?.track(event: message)
return
}

if kind == "foreground" {
if let emitter = shared.emitter {
emitter.sendEvent(withName: NotificationType.notificationReceived.rawValue, body: ["payload": payload, "kind": "foreground"])
} else {
shared.logger?.track(event: "Fatal: Emitter not found. \(#function)")
}
} else if kind == "background" {
guard let completionHandler = notification.userInfo?["completionHandler"] as? (UIBackgroundFetchResult) -> Void else {
guard let completionHandler = payload["completionHandler"] as? (UIBackgroundFetchResult) -> Void else {
shared.logger?.track(event: "Fatal: Completion handler not found. \(#function)")
return
}
Expand Down Expand Up @@ -174,25 +151,15 @@ extension Push {

}

@objc func handleRemoteNotificationsRegistered(_ notification: Notification) {
guard let deviceToken = notification.userInfo?["deviceToken"] as? String else {
shared.logger?.track(event: "Fatal: Device token not found. \(#function)")
return
}

@objc func handleRemoteNotificationsRegistered(deviceToken: String) {
if let emitter = shared.emitter {
emitter.sendEvent(withName: NotificationType.deviceTokenReceived.rawValue, body: deviceToken)
} else {
shared.logger?.track(event: "Fatal: Emitter not found. \(#function)")
}
}

@objc func handleRemoteNotificationRegistrationError(_ notification: Notification) {
guard let error = notification.userInfo?["error"] as? String else {
shared.logger?.track(event: "Fatal: error not found. \(#function)")
return
}

@objc func handleRemoteNotificationRegistrationError(error: String) {
if let emitter = shared.emitter {
emitter.sendEvent(withName: NotificationType.errorReceived.rawValue, body: error)
} else {
Expand All @@ -209,44 +176,27 @@ extension Push: UNUserNotificationCenterDelegate {
return String(format: "%02x", data)
}
let token = tokenParts.joined()
NotificationCenter.default.post(
name: Notification.Name(NotificationType.deviceTokenReceived.rawValue),
object: nil,
userInfo: ["deviceToken": token]
)
shared.logger?.track(event: "Device token received: \(token)")
handleRemoteNotificationsRegistered(deviceToken: token)
}

public func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
NotificationCenter.default.post(
name: Notification.Name(NotificationType.errorReceived.rawValue),
object: nil,
userInfo: ["error": error.localizedDescription]
)
shared.logger?.track(event: "Error registering for remote notifications: \(error.localizedDescription)")
handleRemoteNotificationRegistrationError(error: error.localizedDescription)
}

public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
NotificationCenter.default.post(
name: Notification.Name(NotificationType.notificationReceived.rawValue),
object: nil,
userInfo: ["payload": notification.request.content.userInfo, "kind": "foreground"]
)
handleRemoteNotificationReceived(payload: notification.request.content.userInfo, kind: "foreground")
completionHandler([.banner, .sound, .badge, .list])
}

public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
NotificationCenter.default.post(
name: Notification.Name(NotificationType.notificationReceived.rawValue),
object: nil,
userInfo: ["payload": response.notification.request.content.userInfo, "kind": "opened"]
)
handleRemoteNotificationReceived(payload: response.notification.request.content.userInfo, kind: "opened")
}

public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
NotificationCenter.default.post(
name: Notification.Name(NotificationType.notificationReceived.rawValue),
object: nil,
userInfo: ["payload": userInfo, "kind": "background", "completionHandler": completionHandler]
)
let payload: [String : Any] = ["payload": userInfo, "kind": "background", "completionHandler": completionHandler]
handleRemoteNotificationReceived(payload: payload, kind: "background")
}

}
3 changes: 1 addition & 2 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,5 +103,4 @@ class Push {
}
}

const push = new Push();
export default push;
export default Push;

0 comments on commit eff717f

Please sign in to comment.