Swift (iOS)
«`swift
import UserNotifications
class NotificationManager {
func requestAuthorization() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
// Authorization granted
} else {
// Authorization denied
}
}
}
func scheduleNotification(title: String, body: String, date: Date) {
let center = UNUserNotificationCenter.current()
let notificationContent = UNMutableNotificationContent()
notificationContent.title = title
notificationContent.body = body
notificationContent.sound = UNNotificationSound.default
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: notificationContent, trigger: trigger)
center.add(request) { (error) in
if let error = error {
// Handle error
}
}
}
}
«`
Kotlin (Android)
«`kotlin
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import androidx.core.app.NotificationCompat
class NotificationManager(private val context: Context) {
private val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(«my_channel_id», «Notification Title», NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
}
fun showNotification(title: String, body: String, intent: Intent) {
val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val notification = NotificationCompat.Builder(context, «my_channel_id»)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_notification)
.setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.ic_notification))
.setContentIntent(pendingIntent)
.build()
notificationManager.notify(1234, notification)
}
}
«`