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

Added WebView example #89

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -16,55 +16,31 @@ import com.facebook.react.ReactInstanceManager
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.soloader.SoLoader
import com.exampleapp.NotificationPackage
import com.facebook.react.ReactHost
import com.facebook.react.modules.core.DeviceEventManagerModule
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost

class MainApplication : Application(), ReactApplication {

override val reactNativeHost: ReactNativeHost =
object : ReactNativeHost(this) {
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
add(NotificationPackage())
}
PackageList(this).packages.apply {}
override fun getJSMainModuleName(): String = "index"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
}

override val reactHost: ReactHost
get() = getDefaultReactHost(this.applicationContext, reactNativeHost)

override fun onCreate() {
super.onCreate()
//The fifth step of https://developers.mindbox.ru/docs/firebase-send-push-notifications-react-native
Mindbox.initPushServices(this, listOf(MindboxFirebase, MindboxHuawei))
SoLoader.init(this, false)
}

private val gson = Gson()

fun saveNotification(message: MindboxRemoteMessage) {
val sharedPreferences = getSharedPreferences("notifications", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
val notificationsJson = sharedPreferences.getString("notifications", "[]")
val type = object : TypeToken<MutableList<String>>() {}.type
val notifications: MutableList<String> = gson.fromJson(notificationsJson, type)
notifications.add(gson.toJson(message))
editor.putString("notifications", gson.toJson(notifications))
editor.apply()
notifyJS()
}

private fun notifyJS() {
val handler = Handler(Looper.getMainLooper())
handler.post {
try {
val reactInstanceManager = reactNativeHost.reactInstanceManager
reactInstanceManager.currentReactContext
?.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
?.emit("newNotification", null)
} catch (e: Exception) {
Log.e("MainApplication", "Error notifying React Native", e)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,6 @@ class MindboxFirebaseMessagingService : FirebaseMessagingService() {
channelDescription = channelDescription
)

// https://developers.mindbox.ru/docs/android-sdk-methods#converttomindboxremotemessage-since-284
val mindboxMessage = MindboxFirebase.convertToMindboxRemoteMessage(remoteMessage)
if (mindboxMessage != null) {
val app = applicationContext as MainApplication
app.saveNotification(mindboxMessage)
}

// If the push notification was not from Mindbox or contains incorrect data, a fallback can be implemented for its handling
if (!messageWasHandled) {
Log.d("PushNotification", "Received an unsupported or incorrect push notification.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,6 @@ class MindboxHuaweiMessagingService : HmsMessageService() {
channelDescription = channelDescription
)

// https://developers.mindbox.ru/docs/android-sdk-methods#converttomindboxremotemessage-since-284
val mindboxMessage = MindboxHuawei.convertToMindboxRemoteMessage(remoteMessage)
if (mindboxMessage != null) {
val app = applicationContext as MainApplication
app.saveNotification(mindboxMessage)
}

// If the push notification was not from Mindbox or contains incorrect data, a fallback can be implemented for its handling
if (!messageWasHandled) {
Log.d("PushNotification", "Received an unsupported or incorrect push notification.")
Expand Down

This file was deleted.

This file was deleted.

4 changes: 2 additions & 2 deletions example/exampleApp/android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ buildscript {
compileSdkVersion = 34
targetSdkVersion = 34
ndkVersion = "25.1.8937393"
kotlinVersion = "1.8.0"
kotlinVersion = "1.9.22"
}
repositories {
google()
mavenCentral()
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
classpath("com.android.tools.build:gradle:4.2.1")
classpath("com.android.tools.build:gradle:8.6.0")
classpath("com.facebook.react:react-native-gradle-plugin:7.5")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin")
classpath 'com.google.gms:google-services:4.3.14'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Expand Down
14 changes: 1 addition & 13 deletions example/exampleApp/ios/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD

return true
}
func notifyReactNative() {
if let bridge = bridge, let eventEmitter = bridge.module(for: NotificationModule.self) as? NotificationModule {
eventEmitter.notifyReactNative()
}
}

// Handling remote notification fetch completion
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
Mindbox.shared.application(application, performFetchWithCompletionHandler: completionHandler)
notifyReactNative()
}

// Updating APNS token in Mindbox
Expand All @@ -72,7 +67,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD

// Displaying notifications when the app is active
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
notifyReactNative()
completionHandler([.alert, .sound, .badge])
}

Expand Down Expand Up @@ -102,10 +96,4 @@ extension AppDelegate: RCTBridgeDelegate {
return Bundle.main.url(forResource: "main", withExtension: "jsbundle")
#endif
}

func extraModules(for bridge: RCTBridge!) -> [RCTBridgeModule]! {
var modules = [RCTBridgeModule]()
modules.append(NotificationModule())
return modules
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,62 +4,17 @@ import MindboxNotifications
// https://developers.mindbox.ru/docs/ios-send-rich-push-react-native
class NotificationService: UNNotificationServiceExtension {

static let suiteName = "group.cloud.Mindbox.com.mindbox.exampleRN"
// Lazy initialization of MindboxNotificationService
lazy var mindboxService = MindboxNotificationService()

// Handles the received notification request and modifies the content accordingly.
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
// Processing the incoming notification
mindboxService.didReceive(request, withContentHandler: contentHandler)
saveNotification(request: request)
}

override func serviceExtensionTimeWillExpire() {
// Handling expiration of service extension time
mindboxService.serviceExtensionTimeWillExpire()
}

// save data from notification to userDefaults
// don't use userDefault on your application, it's only for example
func saveNotification(request: UNNotificationRequest) {
guard let pushData = mindboxService.getMindboxPushData(userInfo: request.content.userInfo) else {
print("Failed to get Mindbox push data")
return
}

let mindboxRemoteMessage = MindboxRemoteMessage(
uniqueKey: pushData.uniqueKey ?? UUID().uuidString,
title: pushData.aps?.alert?.title ?? "",
description: pushData.aps?.alert?.body ?? "",
pushLink: pushData.clickUrl,
imageUrl: pushData.imageUrl,
pushActions: pushData.buttons?.map { PushAction(uniqueKey: $0.uniqueKey ?? UUID().uuidString, text: $0.text ?? "", url: $0.url ?? "") } ?? [],
payload: pushData.payload
)

let userDefaults = UserDefaults(suiteName: NotificationService.suiteName)
let notificationsJson = userDefaults?.string(forKey: "notifications") ?? "[]"

do {
var notifications = try JSONDecoder().decode([String].self, from: Data(notificationsJson.utf8))

let jsonData = try JSONEncoder().encode(mindboxRemoteMessage)
if let jsonString = String(data: jsonData, encoding: .utf8) {
notifications.append(jsonString)
} else {
print("Failed to encode mindboxRemoteMessage to String")
}

let updatedNotificationsData = try JSONEncoder().encode(notifications)
if let updatedNotificationsString = String(data: updatedNotificationsData, encoding: .utf8) {
userDefaults?.set(updatedNotificationsString, forKey: "notifications")
} else {
print("Failed to encode updated notifications to String")
}
} catch {
print("Error processing notifications: \(error)")
}
userDefaults?.synchronize()
}
}
11 changes: 0 additions & 11 deletions example/exampleApp/ios/Models/MindboxRemoteMessage.swift

This file was deleted.

7 changes: 0 additions & 7 deletions example/exampleApp/ios/Models/PushAction.swift

This file was deleted.

7 changes: 0 additions & 7 deletions example/exampleApp/ios/NotificationModule.m

This file was deleted.

47 changes: 0 additions & 47 deletions example/exampleApp/ios/NotificationModule.swift

This file was deleted.

Loading
Loading