Skip to content

Commit

Permalink
- check for tasks regularly (ios impl) + fix debug log calls
Browse files Browse the repository at this point in the history
  • Loading branch information
rodvar committed Dec 9, 2024
1 parent 38346d3 commit 9dce84b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package network.bisq.mobile.domain.service.controller
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import network.bisq.mobile.utils.Logging
import platform.BackgroundTasks.*
Expand All @@ -18,13 +19,14 @@ actual class NotificationServiceController: ServiceController, Logging {

companion object {
const val BACKGROUND_TASK_ID = "network.bisq.mobile.iosUC4273Y485"
const val CHECK_NOTIFICATIONS_DELAY = 15 * 10000L
}

private var isRunning = false
private var isBackgroundTaskRegistered = false
private val logScope = CoroutineScope(Dispatchers.Main)

init {
private fun setupDelegate() {
val delegate = object : NSObject(), UNUserNotificationCenterDelegateProtocol {
override fun userNotificationCenter(
center: UNUserNotificationCenter,
Expand All @@ -46,37 +48,38 @@ actual class NotificationServiceController: ServiceController, Logging {
// Handle the response when the user taps the notification
withCompletionHandler()
}

}

UNUserNotificationCenter.currentNotificationCenter().delegate = delegate
logDebug("Notification center delegate applied")
}


actual override fun startService() {
if (isRunning) {
return
}
registerBackgroundTask()
logDebug("Starting background service")
UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
UNAuthorizationOptionAlert or UNAuthorizationOptionSound or UNAuthorizationOptionBadge
) { granted, error ->
if (granted) {
println("Notification permission granted.")
logDebug("Notification permission granted.")
setupDelegate()
registerBackgroundTask()
// Once permission is granted, you can start scheduling background tasks
scheduleBackgroundTask()
println("Background service started")
startBackgroundTaskLoop()
logDebug("Background service started")
isRunning = true
} else {
println("Notification permission denied: ${error?.localizedDescription}")
logDebug("Notification permission denied: ${error?.localizedDescription}")
}
}
}

actual override fun stopService() {
BGTaskScheduler.sharedScheduler.cancelAllTaskRequests()
println("Background service stopped")
logDebug("Background service stopped")
isRunning = false
}

Expand All @@ -89,17 +92,17 @@ actual class NotificationServiceController: ServiceController, Logging {

val trigger = UNTimeIntervalNotificationTrigger.triggerWithTimeInterval(5.0, repeats = false)

val requestId = NSUUID().UUIDString
val request = UNNotificationRequest.requestWithIdentifier(
NSUUID().UUIDString, // Generates a unique identifier
requestId,
content,
trigger // Trigger can be set to null for immediate delivery
trigger
)
println("getting called every 10 sec")
UNUserNotificationCenter.currentNotificationCenter().addNotificationRequest(request) { error ->
if (error != null) {
println("Error adding notification request: ${error.localizedDescription}")
logDebug("Error adding notification request: ${error.localizedDescription}")
} else {
println("Notification added successfully")
logDebug("Notification $requestId added successfully")
}
}
}
Expand All @@ -110,11 +113,18 @@ actual class NotificationServiceController: ServiceController, Logging {
}

private fun handleBackgroundTask(task: BGProcessingTask) {
logDebug("Executing background task")
pushNotification("Background Notification", "This notification was triggered in the background")
task.setTaskCompletedWithSuccess(true) // Mark the task as completed
logDebug("Background task completed successfully")
scheduleBackgroundTask() // Re-schedule the next task
}

task.setTaskCompletedWithSuccess(true)
// scheduleBackgroundTask() // Reschedule if needed
private fun startBackgroundTaskLoop() {
CoroutineScope(Dispatchers.Default).launch {
while (isRunning) {
scheduleBackgroundTask()
delay(CHECK_NOTIFICATIONS_DELAY) // Check notifications every min
}
}
}

@OptIn(ExperimentalForeignApi::class)
Expand All @@ -124,20 +134,24 @@ actual class NotificationServiceController: ServiceController, Logging {
earliestBeginDate = NSDate(timeIntervalSinceReferenceDate = 10.0)
}
BGTaskScheduler.sharedScheduler.submitTaskRequest(request, null)
println("Background task scheduled")
logDebug("Background task scheduled")
}

// fun setupTaskHandlers() {
// BGTaskScheduler.sharedScheduler.registerForTaskWithIdentifier(BACKGROUND_TASK_ID, BGProcessingTask.class, ::handleBackgroundTask)
// }


private fun logDebug(message: String) {
logScope.launch {
log.d(message)
log.d { message }
}
}


private fun registerBackgroundTask() {
if (isBackgroundTaskRegistered) {
println("Background task is already registered.")
logDebug("Background task is already registered.")
return
}

Expand All @@ -150,7 +164,6 @@ actual class NotificationServiceController: ServiceController, Logging {
}

isBackgroundTaskRegistered = true
// TODO logger is not working
println("Background task handler registered.")
logDebug("Background task handler registered.")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ import kotlin.random.Random
*/
open class MainPresenter(private val notificationServiceController: NotificationServiceController) :
BasePresenter(null), AppPresenter {
companion object {
const val PUSH_DELAY = 60000L
}

lateinit var navController: NavHostController
private set

Expand Down Expand Up @@ -58,8 +62,8 @@ open class MainPresenter(private val notificationServiceController: Notification
val randomTitle = "Title ${Random.nextInt(1, 100)}"
val randomMessage = "Message ${Random.nextInt(1, 100)}"
notificationServiceController.pushNotification(randomTitle, randomMessage)
println("Pushed: $randomTitle - $randomMessage")
delay(10000) // 10 seconds
log.d {"Pushed: $randomTitle - $randomMessage" }
delay(PUSH_DELAY) // 1 min
}
}
}
Expand Down

0 comments on commit 9dce84b

Please sign in to comment.