Я настраиваю свое уведомление о Flutter, используя плагин Flutter_local_notification, я хочу показать уведомление даже на переднем плане. Для простоты я создал тест, чтобы показать уведомление, когда нажимает кнопка. Настройка такая: < /p>
class NotificationService {
NotificationService._();
static final _instance = NotificationService._();
static NotificationService get instance => _instance;
Stream? forgroundMessagesStream;
Stream? notificationClickedStream;
Stream? tokenUpdatedStream;
static const _channel = AndroidNotificationChannel(
'high_importance_channel',
'High Importance Notifications',
description: 'Urgent notifications',
importance: Importance.max,
);
final FlutterLocalNotificationsPlugin _flnp =
FlutterLocalNotificationsPlugin();
// final fcm = FirebaseMessaging.instance;
final _details = NotificationDetails(
iOS: const DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
presentBanner: true,
presentList: true,
),
android: AndroidNotificationDetails(
_channel.id,
_channel.name,
channelDescription: _channel.description,
importance: Importance.max,
priority: Priority.max,
icon: 'notification_icon',
),
);
Future requestPermissions() async {
await fcm.setForegroundNotificationPresentationOptions(
alert: false,
sound: true,
badge: true,
);
final settings = await fcm.requestPermission(
alert: true,
sound: true,
badge: true,
);
Logger.logDebugInfo(
'requestPermissions | settings: ${settings.authorizationStatus}',
level: LogLevel.notifications,
);
if (Platform.isAndroid) {
final result = await _flnp
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.requestNotificationsPermission();
Logger.logDebugInfo(
'requestPermissions | result: $result',
level: LogLevel.notifications,
);
} else if (Platform.isIOS) {
final result = await _flnp
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
Logger.logDebugInfo(
'requestPermissions | result: $result',
level: LogLevel.notifications,
);
}
}
init() async {
Logger.logDebugInfo(
'init',
level: LogLevel.notifications,
);
// await requestPermissions();
InitializationSettings initializationSettings =
const InitializationSettings(
android: AndroidInitializationSettings(
'notification_icon',
),
iOS: DarwinInitializationSettings(
defaultPresentAlert: true,
defaultPresentBadge: true,
defaultPresentSound: true,
defaultPresentBanner: true,
defaultPresentList: true,
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
),
);
await _flnp.initialize(
initializationSettings,
onDidReceiveNotificationResponse: (details) {
Logger.logDebugInfo("onDidReceiveNotificationResponse");
},
);
if (Platform.isAndroid) {
await _flnp
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(_channel);
}
}
showNotification(NotificationEvent notification) async {
try {
Logger.logDebugInfo(
'NotificationService | showNotification | notification: ${notification.toString()}',
level: LogLevel.notifications,
);
await _flnp.show(
notification.id.hashCode,
notification.title,
notification.message,
_details,
payload: jsonEncode({
'type': notification.type.name,
'payload': jsonEncode(notification.payload.toJson()),
}),
);
} catch (e, s) {
Logger.logException(e, s: s);
}
}
}
< /code>
В приложении delegate.swift: < /p>
import Flutter
import UIKit
import GoogleMaps
@main
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GMSServices.provideAPIKey("AIzaSyCx2Ncf8fdPLKLVGCbJvecpr-jnaApiLeo")
// Register for remote notifications
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
< /code>
Но я все еще не получаю уведомление на переднем плане, чтобы показать! Есть идеи, почему? Установлены параметры разрешения и презентации, он работает на Android, но не iOS.
Подробнее здесь: https://stackoverflow.com/questions/796 ... lutter-ios
Как показать уведомление переднего плана в Flutter (iOS) ⇐ IOS
Программируем под IOS
-
Anonymous
1749458431
Anonymous
Я настраиваю свое уведомление о Flutter, используя плагин Flutter_local_notification, я хочу показать уведомление даже на переднем плане. Для простоты я создал тест, чтобы показать уведомление, когда нажимает кнопка. Настройка такая: < /p>
class NotificationService {
NotificationService._();
static final _instance = NotificationService._();
static NotificationService get instance => _instance;
Stream? forgroundMessagesStream;
Stream? notificationClickedStream;
Stream? tokenUpdatedStream;
static const _channel = AndroidNotificationChannel(
'high_importance_channel',
'High Importance Notifications',
description: 'Urgent notifications',
importance: Importance.max,
);
final FlutterLocalNotificationsPlugin _flnp =
FlutterLocalNotificationsPlugin();
// final fcm = FirebaseMessaging.instance;
final _details = NotificationDetails(
iOS: const DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
presentBanner: true,
presentList: true,
),
android: AndroidNotificationDetails(
_channel.id,
_channel.name,
channelDescription: _channel.description,
importance: Importance.max,
priority: Priority.max,
icon: 'notification_icon',
),
);
Future requestPermissions() async {
await fcm.setForegroundNotificationPresentationOptions(
alert: false,
sound: true,
badge: true,
);
final settings = await fcm.requestPermission(
alert: true,
sound: true,
badge: true,
);
Logger.logDebugInfo(
'requestPermissions | settings: ${settings.authorizationStatus}',
level: LogLevel.notifications,
);
if (Platform.isAndroid) {
final result = await _flnp
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.requestNotificationsPermission();
Logger.logDebugInfo(
'requestPermissions | result: $result',
level: LogLevel.notifications,
);
} else if (Platform.isIOS) {
final result = await _flnp
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
Logger.logDebugInfo(
'requestPermissions | result: $result',
level: LogLevel.notifications,
);
}
}
init() async {
Logger.logDebugInfo(
'init',
level: LogLevel.notifications,
);
// await requestPermissions();
InitializationSettings initializationSettings =
const InitializationSettings(
android: AndroidInitializationSettings(
'notification_icon',
),
iOS: DarwinInitializationSettings(
defaultPresentAlert: true,
defaultPresentBadge: true,
defaultPresentSound: true,
defaultPresentBanner: true,
defaultPresentList: true,
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
),
);
await _flnp.initialize(
initializationSettings,
onDidReceiveNotificationResponse: (details) {
Logger.logDebugInfo("onDidReceiveNotificationResponse");
},
);
if (Platform.isAndroid) {
await _flnp
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(_channel);
}
}
showNotification(NotificationEvent notification) async {
try {
Logger.logDebugInfo(
'NotificationService | showNotification | notification: ${notification.toString()}',
level: LogLevel.notifications,
);
await _flnp.show(
notification.id.hashCode,
notification.title,
notification.message,
_details,
payload: jsonEncode({
'type': notification.type.name,
'payload': jsonEncode(notification.payload.toJson()),
}),
);
} catch (e, s) {
Logger.logException(e, s: s);
}
}
}
< /code>
В приложении delegate.swift: < /p>
import Flutter
import UIKit
import GoogleMaps
@main
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GMSServices.provideAPIKey("AIzaSyCx2Ncf8fdPLKLVGCbJvecpr-jnaApiLeo")
// Register for remote notifications
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
< /code>
Но я все еще не получаю уведомление на переднем плане, чтобы показать! Есть идеи, почему? Установлены параметры разрешения и презентации, он работает на Android, но не iOS.
Подробнее здесь: [url]https://stackoverflow.com/questions/79658600/how-to-show-foreground-notification-in-flutter-ios[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия