### Install via CocoaPods Source: https://multipushed.ru/docs/iOS_library Add the library dependency to your Podfile and run the installation command. ```ruby pod 'PushedMessagingiOSLibrary', :git => 'https://github.com/PushedLab/Pushed.Messaging.iOS.Library.git' ``` ```bash pod install ``` -------------------------------- ### Install Web SDK Source: https://multipushed.ru/docs/webpushed Command to install the required SDK package via npm. ```bash npm install @pushedlab/pushed-web-sdk --save ``` -------------------------------- ### Install Pushed React Native library Source: https://multipushed.ru/docs/reactnativebridge Use npm to install the library directly from the GitHub repository. ```bash npm install github:PushedLab/Pushed.Messaging.ReactNative ``` -------------------------------- ### cURL Request Example Source: https://multipushed.ru/docs/API/statuspush Example of how to perform the request using cURL. ```bash curl https://api.pushed.ru/v2/info/messages \ --request POST \ --header 'Content-Type: application/json' \ --header 'Authorization: ' \ --data '{ "clientToken": null, "pushTargetType": 1, "limit": 1, "offset": 1 }' ``` -------------------------------- ### Locate Podfile Installation Line Source: https://multipushed.ru/docs/flutterplugin Identify the existing flutter_install_all_ios_pods line in the Podfile. ```ruby flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) ``` -------------------------------- ### pushedService.start() Source: https://multipushed.ru/docs/androidlibrary Starts the service to receive messages while the application is in the foreground. ```APIDOC ## pushedService.start(callback) ### Description Starts the service and registers a callback to handle messages received while the app is in the foreground. Returns the client token. ### Parameters - **callback** ((JSONObject) -> Boolean) - Required - A function that receives the message. Return true if handled, false to trigger the default notification and background receiver. ``` -------------------------------- ### startService(serviceName: string) Source: https://multipushed.ru/docs/reactnativebridge Starts the push notification service. Returns a promise that resolves with the device token required for sending push notifications. ```APIDOC ## startService(serviceName: string) ### Description Starts the push notification service. ### Parameters - **serviceName** (string) - Required - The name of the service to start. ### Returns - **Promise** - Resolves with the device token. ``` -------------------------------- ### Start the Pushed messaging service Source: https://multipushed.ru/docs/reactnativebridge Initialize the foreground service using your unique application ID obtained from the Pushed admin panel. ```javascript const handleStart = () => { console.log('Starting Pushed Service'); startService('PushedService', 'YOUR_APPLICATION_ID').then((newToken) => { console.log(`Service has started: ${newToken}`); }); }; ``` -------------------------------- ### Initialize and Manage PushedMessaging Library Source: https://multipushed.ru/docs/iOS_library Methods for library setup, token retrieval, message confirmation, and permission requests. ```swift // Инициализация библиотеки (упрощённая форма) PushedMessagingiOSLibrary.setup(_ appDelegate: UIApplicationDelegate, useAPNS: Bool, enableWebSocket: Bool) // Инициализация (расширенная форма с дополнительными опциями) PushedMessagingiOSLibrary.setup(_ appDelegate: UIApplicationDelegate, askPermissions: Bool = true, loggerEnabled: Bool = false, useAPNS: Bool = true, enableWebSocket: Bool = false) // Получение клиентского токена let token = PushedMessagingiOSLibrary.clientToken // Подтверждение сообщения по клику PushedMessagingiOSLibrary.confirmMessage(_ response: UNNotificationResponse) // Запрос разрешений на уведомления (если нужно вручную) PushedMessagingiOSLibrary.requestNotificationPermissions() // Получение логов (для отладки) let logs = PushedMessagingiOSLibrary.getLog() ``` -------------------------------- ### Broadcast Web Push cURL Example Source: https://multipushed.ru/docs/API/webbroadcast Example of a cURL command to trigger a broadcast notification, requiring an Authorization Bearer token. ```bash curl --request POST \ --url https://pub.multipushed.ru/v2/publish-broadcast-web-push \ --header 'Authorization: Bearer YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "title": "Broadcast Notification", "url": "https://multipushed.ru/", "body": "Сообщение для всех", "image": "https://example.com/image.png", "groupid": "66d199c1885e451134479574" }' ``` -------------------------------- ### cURL Request for Client Token Info Source: https://multipushed.ru/docs/API/statuspush Example cURL command to fetch mobile client token information. ```bash curl https://api.pushed.ru/v2/info/mobile-client-token \ --request POST \ --header 'Content-Type: application/json' \ --header 'Authorization: YOUR_SECRET_TOKEN' \ --data '{ "clientToken": "dgdg" }' ``` -------------------------------- ### Customer Information Response Source: https://multipushed.ru/docs/API/customers Example JSON response structure for a successful customer information request. ```json { "success": true, "message": null, "errCode": null, "model": { "id": null, "phone": null, "customFields": "", "clientTokens": [ { "clientToken": null, "createDate": "2025-07-10T13:35:56.386Z", "applicationId": null, "possibleTransports": [ "Pushed" ], "sdkVersion": null, "operatingSystem": null, "mobileDeviceName": null, "backgroundWorkPermission": null, "displayPushNotificationsPermission": null, "lastUpdateDate": "2025-07-10T13:35:56.386Z" } ] } } ``` -------------------------------- ### Client Token Info Response Source: https://multipushed.ru/docs/API/statuspush Example JSON response containing mobile client token details. ```json { "success": true, "message": null, "errCode": null, "model": { "createDate": "2025-05-26T06:31:41.732Z", "applicationId": null, "isWebSocketOpen": true, "suspended": true, "possibleTransports": [ "Pushed" ], "sdkVersion": null, "operatingSystem": null, "backgroundWorkPermission": true, "displayPushNotificationsPermission": true, "lastUpdateDate": "2025-05-26T06:31:41.732Z", "customerInfo": { "phone": null }, "geolocationInfo": { "region": null, "timeZone": null } } } ``` -------------------------------- ### cURL Request for Push Message Info Source: https://multipushed.ru/docs/API/statuspush Example cURL command to fetch push message information. ```bash curl https://api.pushed.ru/v2/info/message \ --request POST \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIwMzA2MDQxMjIsImF1ZCI6IjY2MzllOTVhYzQ1YTM5M2U1ZGYzYTI4MyJ9.DD5ailxSD0N56KzYFePxEnxXSSPGuS1o6UGWzlK25oc' \ --data '{ "messageId": "683401664030f74a083b6554", "targetType": 1 }' ``` -------------------------------- ### GET https://api.multipushed.ru/v2/info/customer Source: https://multipushed.ru/docs/API/customers Retrieves information about a specific customer. ```APIDOC ## GET https://api.multipushed.ru/v2/info/customer ### Description Retrieves detailed information about a customer, including their custom fields and associated client tokens. ### Method GET ### Endpoint https://api.multipushed.ru/v2/info/customer ### Parameters #### Query Parameters - **customerId** (string) - Required - The unique identifier of the customer. ### Response #### Success Response (200) - **success** (boolean) - Result of the request execution. - **message** (string) - Error description if an error occurs. - **errCode** (string) - Error code if an error occurs. - **model** (object) - Customer data model. ### Response Example { "success": true, "message": null, "errCode": null, "model": { "id": null, "phone": null, "customFields": "", "clientTokens": [ { "clientToken": null, "createDate": "2025-07-10T13:35:56.386Z", "applicationId": null, "possibleTransports": ["Pushed"], "sdkVersion": null, "operatingSystem": null, "mobileDeviceName": null, "backgroundWorkPermission": null, "displayPushNotificationsPermission": null, "lastUpdateDate": "2025-07-10T13:35:56.386Z" } ] } } ``` -------------------------------- ### Push Message Info Response Source: https://multipushed.ru/docs/API/statuspush Example JSON response containing push message status details. ```json { "success": true, "message": null, "errCode": null, "model": [ { "messageId": null, "transportKind": 1, "pushState": 1, "incidentMessage": null, "processingDate": null } ] } ``` -------------------------------- ### Bind Token to Application ID Source: https://multipushed.ru/docs/iOS_library Call this method immediately after setup to associate the client token with a specific application ID. ```swift // Сразу после PushedMessagingiOSLibrary.setup(...) PushedMessagingiOSLibrary.refreshTokenWithApplicationId("YOUR_APPLICATION_ID") ``` -------------------------------- ### refreshTokenWithApplicationId(applicationId: String) Source: https://multipushed.ru/docs/iOS_library Binds the client token to a specific application ID. This should be called immediately after the library setup. ```APIDOC ## refreshTokenWithApplicationId(applicationId: String) ### Description Binds the client token to a specific application ID. If the provided string is empty or nil, the token will be bound to the application marked as Default in the Pushed dashboard. ### Parameters - **applicationId** (String) - Required - The unique identifier of the application to bind the token to. ``` -------------------------------- ### PushedMessagingiOSLibrary.setup Source: https://multipushed.ru/docs/iOS_library Initializes the library with the provided application delegate and configuration options. ```APIDOC ## PushedMessagingiOSLibrary.setup ### Description Initializes the library. The simplified form uses default values, while the extended form allows manual configuration of permissions, logging, APNS, and WebSocket usage. ### Signature `static func setup(_ appDelegate: UIApplicationDelegate, useAPNS: Bool, enableWebSocket: Bool)` `static func setup(_ appDelegate: UIApplicationDelegate, askPermissions: Bool = true, loggerEnabled: Bool = false, useAPNS: Bool = true, enableWebSocket: Bool = false)` ``` -------------------------------- ### PushedMessagingiOSLibrary.setup Source: https://multipushed.ru/docs/iOS_library Initializes the library with specific messaging configurations. ```APIDOC ## PushedMessagingiOSLibrary.setup(delegate, useAPNS, enableWebSocket) ### Description Configures the library with the specified delegate and messaging modes. ### Parameters - **delegate** (Any) - The object acting as the delegate. - **useAPNS** (Bool) - Whether to enable APNS push notifications. - **enableWebSocket** (Bool) - Whether to enable WebSocket connectivity. ``` -------------------------------- ### Get Customer Information Request Source: https://multipushed.ru/docs/API/customers Retrieves customer details using a GET request. Requires a valid Authorization token. ```http GET https://api.multipushed.ru/v2/info/customer ``` ```bash curl 'https://api.multipushed.ru/v2/info/customer?customerId=customerId' \ --header 'Authorization: YOUR_SECRET_TOKEN' ``` -------------------------------- ### Initialize Plugin Correctly Source: https://multipushed.ru/docs/flutterplugin Ensure WidgetsFlutterBinding is initialized and the plugin is awaited during application startup. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); // ← Важно! await FlutterPushedMessaging.init(backgroundMessage); // ← Await! runApp(MyApp()); } ``` -------------------------------- ### Настройка AppDelegate для iOS Source: https://multipushed.ru/docs/flutterplugin Настройте делегат уведомлений в методе didFinishLaunchingWithOptions вашего AppDelegate. ```swift if #available(iOS 10.0, *) { UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate } ``` -------------------------------- ### POST https://api.multipushed.ru/v2/management/client-token (Get) Source: https://multipushed.ru/docs/API/changetokensgroup Получение списка токенов, входящих в группу. ```APIDOC ## POST https://api.multipushed.ru/v2/management/client-token ### Description Получение списка токенов, входящих в группу. ### Method POST ### Endpoint https://api.multipushed.ru/v2/management/client-token ### Request Body - **operation** (string) - Required - Тип операции: "Get" - **groupId** (string) - Required - Идентификатор группы - **type** (string/number) - Required - Тип группы: "Mobile" (1) или "Web" (2) ### Request Example { "operation": "Get", "groupId": "", "type": "Mobile" } ### Response #### Success Response (200) - **model** (array) - Список токенов - **success** (boolean) - Статус выполнения #### Response Example { "model": ["3SFoZ0ShMPxDU5UaOjsluzinArYciMe1", "RBbUFdTVJfu2yig8BhpOx1HyEKiPwMxt"], "success": true, "message": null, "errCode": null } ``` -------------------------------- ### Handle Foreground Messages Source: https://multipushed.ru/docs/androidlibrary Start the service in onResume to process messages while the application is in the foreground. ```kotlin override fun onResume() { super.onResume() // token - это ваш клиентский токен для отправки пушей этому конкретному пользователю. val token = pushedService.start { message -> Log.d("MyActivity", "Получено сообщение в активном приложении: $message") // Верните true, если сообщение обработано. // Если вы вернете false, библиотека покажет уведомление // и передаст сообщение вашему обработчику onBackgroundMessage. true } Log.d("MyActivity", "Клиентский токен: $token") } ``` -------------------------------- ### Suspended Tokens Response Source: https://multipushed.ru/docs/API/customers Example JSON response structure for a successful suspended tokens request. ```json { "success": true, "message": null, "errCode": null, "model": { "limit": 1, "offset": 1, "data": [ { "clientToken": null, "createDate": "2025-07-10T13:36:04.115Z", "applicationId": null, "possibleTransports": [ "Pushed" ], "sdkVersion": null, "operatingSystem": null, "mobileDeviceName": null, "backgroundWorkPermission": null, "displayPushNotificationsPermission": null, "lastUpdateDate": "2025-07-10T13:36:04.115Z" } ] } } ``` -------------------------------- ### Исключение неиспользуемых провайдеров Source: https://multipushed.ru/docs/androidlibrary Оптимизируйте размер приложения, исключая ненужные зависимости пуш-провайдеров в build.gradle. ```gradle dependencies { implementation('com.github.PushedLab:Pushed.Messaging.Android.Library:1.5.1') { // Пример: Исключить HPK и RuStore, оставив только FCM exclude group: 'com.huawei.hms', module: 'push' exclude group: 'ru.rustore.sdk', module: 'pushclient' exclude group: 'com.google.firebase', module: 'firebase-messaging' } } ``` -------------------------------- ### Configure iOS Build Source: https://multipushed.ru/docs/flutterplugin Run this command in the project root to configure the iOS build environment. ```bash # Выполните это в корне вашего проекта flutter build ios --config-only ``` -------------------------------- ### POST /v2/publish-web-push/ Source: https://multipushed.ru/docs/API/sendwebpush Отправка web push-сообщения конкретному клиенту. ```APIDOC ## POST /v2/publish-web-push/ ### Description Отправляет push-уведомление пользователю. Рекомендуется использовать заголовок до 40 символов и сообщение до 80 символов. ### Method POST ### Endpoint https://pub.multipushed.ru/v2/publish-web-push/ ### Parameters #### Path Parameters - **clientToken** (string) - Required - Уникальный токен клиента. #### Request Body - **title** (string) - Optional - Текст заголовка пуш-сообщения. - **body** (string) - Optional - Основной текст пуш-сообщения. - **payload** (string) - Optional - Нетипизированное сообщение. Заполняется ИЛИ payload ИЛИ title + body. - **url** (string) - Optional - URL страницы, которая открывается при нажатии на пуш. - **image** (string) - Optional - URL иконки пуш-сообщения. - **placeholderImage** (string) - Optional - URL заглавного изображения пуш-сообщения. - **pushActions** (array) - Optional - Кнопки действий (максимум 2). - **silent** (boolean) - Optional - Если true, пуш-сообщение не будет отображено пользователю. ### Request Example { "title": "Test Notification", "url": "https://multipushed.ru/", "body": "Добрый день", "image": "https://example.com/image.png" } ### Response #### Success Response (200) - **model** (object) - Данные ответа (id, createdAt, sentAt, messageStatus). - **success** (boolean) - Результат выполнения запроса. - **message** (string) - Текстовое описание ошибки (если есть). - **errCode** (integer) - Код ошибки (если есть). #### Response Example { "model": { "id": "66d5a0bb6a1dc7d467d1adee", "createdAt": "2024-09-02T11:25:47.8329958Z", "sentAt": null, "messageStatus": "InProcess" }, "success": true, "message": null, "errCode": null } ``` -------------------------------- ### Configure Full Mode (APNS + WebSocket) Source: https://multipushed.ru/docs/iOS_library Initialize or switch to a mode using both APNS and WebSockets. ```swift // Через setup: PushedMessagingiOSLibrary.setup(self, useAPNS: true, enableWebSocket: true) // Или включить на лету: PushedMessagingiOSLibrary.enableAPNS() if PushedMessagingiOSLibrary.isWebSocketAvailable { PushedMessagingiOSLibrary.enableWebSocket() } ``` -------------------------------- ### Настройка репозиториев в settings.gradle Source: https://multipushed.ru/docs/androidlibrary Добавьте необходимые репозитории в корневой файл settings.gradle для корректной загрузки зависимостей. ```gradle // settings.gradle dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() maven { url 'https://jitpack.io' } maven { url 'https://developer.huawei.com/repo/' } // Нужен для HPK } } ``` -------------------------------- ### Configure AppDelegate for Pushed Messaging Source: https://multipushed.ru/docs/iOS_library Initialize the library in your AppDelegate and implement delegate methods for handling push notifications and WebSocket events. ```swift import SwiftUI import PushedMessagingiOSLibrary class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { // Настройка делегата для уведомлений UNUserNotificationCenter.current().delegate = self // Инициализация библиотеки (упрощённый вызов) // Режимы: // - useAPNS: true + enableWebSocket: true → APNS + WebSocket (оба канала) // - useAPNS: false + enableWebSocket: true → Только WebSocket (без APNS) // - useAPNS: true + enableWebSocket: false → Только APNS PushedMessagingiOSLibrary.setup(self, useAPNS: true, enableWebSocket: true) // Дополнительно: настройка коллбеков WebSocket (iOS 13.0+) if PushedMessagingiOSLibrary.isWebSocketAvailable { setupWebSocketCallbacks() } return true } // Получение клиентского токена @objc func isPushedInited(didRecievePushedClientToken pushedToken: String) { print("Client token: \(pushedToken)") // Сохраните токен для отправки сообщений конкретному пользователю } // Обработка входящих push-уведомлений func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { print("Received push notification: \(userInfo)") completionHandler(.newData) } // Обработка клика по уведомлению func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("User clicked notification: \(response.notification.request.content.userInfo)") // Подтверждение взаимодействия с уведомлением PushedMessagingiOSLibrary.confirmMessage(response) completionHandler() } // Настройка WebSocket callbacks private func setupWebSocketCallbacks() { // Отслеживание статуса соединения PushedMessagingiOSLibrary.onWebSocketStatusChange = { status in print("WebSocket status: \(status.rawValue)") } // Обработка входящих WebSocket сообщений PushedMessagingiOSLibrary.onWebSocketMessageReceived = { messageJson in print("WebSocket message received: \(messageJson)") // Обработайте сообщение в вашем приложении // Верните true если сообщение обработано, false для показа стандартного уведомления return self.handleWebSocketMessage(messageJson) } } private func handleWebSocketMessage(_ messageJson: String) -> Bool { // Ваша логика обработки WebSocket сообщений do { let data = messageJson.data(using: .utf8)! let message = try JSONSerialization.jsonObject(with: data) as? [String: Any] // Обработка сообщения... return true // Сообщение обработано } catch { print("Error parsing WebSocket message: \(error)") return false // Показать стандартное уведомление } } } ``` -------------------------------- ### Accessing Notification Payload Data Source: https://multipushed.ru/docs/webpushed Example of a JSON payload and how to extract specific fields from the data object provided by the listener. ```json {"id": 1, "body": "Добрый день"} ``` ```javascript let id = data.id; let body = data.body; ``` -------------------------------- ### Добавление зависимости библиотеки Source: https://multipushed.ru/docs/androidlibrary Подключите библиотеку Pushed Messaging в файле build.gradle вашего приложения. ```gradle dependencies { implementation 'com.github.PushedLab:Pushed.Messaging.Android.Library:1.5.1' // Проверьте последнюю версию } ``` -------------------------------- ### Import Pushed library modules Source: https://multipushed.ru/docs/reactnativebridge Import the necessary service methods and types required for push notification management. ```javascript import { startService, stopService, PushedEventTypes, Push, } from 'pushed-react-native'; ``` -------------------------------- ### Clean and Rebuild iOS Project Source: https://multipushed.ru/docs/flutterplugin Use these commands to perform a clean build and update CocoaPods dependencies for iOS. ```bash # Очистка и пересборка flutter clean cd ios && pod install flutter build ios --config-only ``` -------------------------------- ### Get Suspended Tokens Request Source: https://multipushed.ru/docs/API/customers Retrieves a list of suspended tokens using a POST request. The request body supports pagination and filtering by customer ID and date range. ```http POST https://api.multipushed.ru/v2/info/suspended-tokens ``` ```json { "customerId": null, "dateFrom": null, "dateTo": null, "limit": 1, "offset": 1 } ``` ```bash curl https://api.multipushed.ru/v2/info/suspended-tokens \ --request POST \ --header 'Content-Type: application/json' \ --header 'Authorization: YOUR_SECRET_TOKEN' \ --data '{ "customerId": null, "dateFrom": null, "dateTo": null, "limit": 1, "offset": 1 }' ``` -------------------------------- ### Initialize PushedService Source: https://multipushed.ru/docs/androidlibrary Instantiate the PushedService within an Activity or Application class to enable push provider detection. ```kotlin // в onCreate вашей Activity pushedService = PushedService( context = this, messageReceiverClass = MyMessageReceiver::class.java, channel = "messages" // Канал уведомлений для пушей, отображаемых библиотекой ) ``` -------------------------------- ### Configure Notification Settings Source: https://multipushed.ru/docs/iOS_library Settings to manage notification confirmation behavior and enable detailed logging. ```swift // Отключить дублирование подтверждений (если используется Extension) PushedMessagingiOSLibrary.extensionHandlesConfirmation = true // Включить подробное логирование (пример): PushedMessagingiOSLibrary.setup(self, askPermissions: true, loggerEnabled: true, useAPNS: true, enableWebSocket: false) ``` -------------------------------- ### Implement NotificationService.swift Source: https://multipushed.ru/docs/reactnativebridge Full implementation of the Notification Service Extension to process incoming push notifications and handle message delivery confirmation. ```swift import UserNotifications import Foundation import pushed_react_native_extension @objc(NotificationService) class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive( _ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void ) { self.contentHandler = contentHandler bestAttemptContent = request.content.mutableCopy() as? UNMutableNotificationContent guard let bestAttemptContent else { contentHandler(request.content) return } NSLog("[Extension] didReceiveNotificationRequest called with userInfo: \(request.content.userInfo)") // Обрабатываем messageId через helper: сохраняет в App Group и подтверждает доставку if let messageId = request.content.userInfo["messageId"] as? String { NSLog("[Extension] Found messageId: \(messageId), delegating to PushedIosLib") PushedExtensionHelper.processMessage(messageId) } else { NSLog("[Extension] No messageId found in notification") } // Всегда возвращаем контент системе contentHandler(bestAttemptContent) } override func serviceExtensionTimeWillExpire() { if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } } ``` -------------------------------- ### Implement NotificationService.swift Source: https://multipushed.ru/docs/flutterplugin Replace the default NotificationService content to handle push notification processing via the plugin. ```swift import UserNotifications import flutter_pushed_messaging class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) FlutterPushedMessagingPlugin.confirmExtension(userInfo: request.content.userInfo) if let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } override func serviceExtensionTimeWillExpire() { // Вызывается непосредственно перед завершением extension системой. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } } ``` -------------------------------- ### Connect to WebSocket Source: https://multipushed.ru/docs/notifications Establishes a WebSocket connection to receive real-time notifications. Requires an access token for authentication. ```APIDOC ## WebSocket Connection ### Endpoint `wss://notify.multipushed.ru/web-socket-notification/open-notification-ws` ### Authentication - **Authorization**: Bearer ``` -------------------------------- ### Add Extension Target to Podfile Source: https://multipushed.ru/docs/flutterplugin Define the extension target in the Podfile to inherit search paths. ```ruby target 'extension' do # ← Замените 'extension' на фактическое имя вашего extension inherit! :search_paths end ``` -------------------------------- ### Enable Extension Confirmation Handling Source: https://multipushed.ru/docs/iOS_library Configure the main application to signal that the Notification Service Extension is responsible for processing delivery confirmations. ```swift // Указать что Extension обрабатывает подтверждения PushedMessagingiOSLibrary.extensionHandlesConfirmation = true ``` -------------------------------- ### Configure Podfile for Notification Service Extension Source: https://multipushed.ru/docs/reactnativebridge Add the Pushed extension dependency to your Podfile specifically for the Notification Service Extension target. ```ruby target 'AppNotiService' do pod 'pushed-react-native-extension', :path => '../node_modules/@PushedLab/pushed-react-native' end ``` -------------------------------- ### Registering Website Identifier Source: https://multipushed.ru/docs/webpushed Configure the website identifier to link the client token to your account. This configuration is used for both registration and subscription validation. ```javascript let config = { websiteId: 'your id'}; Pushed.registerWebPushes(config); // аналогично Pushed.validateSubscription(config) ``` -------------------------------- ### Initialize FlutterPushedMessaging plugin Source: https://multipushed.ru/docs/flutterplugin Initialize the plugin in the main function before running the app. Ensure WidgetsFlutterBinding is initialized first. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); // Инициализация плагина await FlutterPushedMessaging.init( backgroundMessage, notificationChannel: "messages", // Только для Android askPermissions: true, // Автозапрос разрешений loggerEnabled: false, // Включите для отладки applicationId: "YOUR_APP_ID", // Кастомный идентификатор (опционально) ); // Получение уникального токена клиента print("Токен клиента: ${FlutterPushedMessaging.token}"); runApp(const MyApp()); } ``` -------------------------------- ### Настройка разрешений в .desktop файле Source: https://multipushed.ru/docs/auroralibrary Добавляет необходимые права доступа для работы с сетью и пуш-уведомлениями. ```ini [X-Application] Permissions=PushNotifications;Internet ``` -------------------------------- ### FlutterPushedMessaging.init Source: https://multipushed.ru/docs/flutterplugin Initializes the messaging plugin with configuration settings including background message handlers and notification channels. ```APIDOC ## FlutterPushedMessaging.init ### Description Initializes the plugin. This must be called before using other plugin features. ### Signature `static Future init(Function(Map) backgroundMessage, {String? notificationChannel, bool? askPermissions, bool? loggerEnabled, String? applicationId})` ### Parameters - **backgroundMessage** (Function) - Required - Callback function executed when a message is received in the background. - **notificationChannel** (String) - Optional - Android-specific notification channel ID. - **askPermissions** (bool) - Optional - Whether to automatically request permissions upon initialization. - **loggerEnabled** (bool) - Optional - Enables or disables internal logging. - **applicationId** (String) - Optional - Custom application identifier. ``` -------------------------------- ### Update iOS Dependencies Source: https://multipushed.ru/docs/flutterplugin Execute this command in the ios directory to update pods. ```bash cd ios pod update ``` -------------------------------- ### PushedService Initialization Source: https://multipushed.ru/docs/androidlibrary Initializes the PushedService instance within an Activity or Application class. ```APIDOC ## PushedService(context, messageReceiverClass, channel, enableLogger, askPermissions, applicationId) ### Description Creates an instance of the PushedService to manage push notifications and background message processing. ### Parameters - **context** (Context) - Required - The application context. - **messageReceiverClass** (Class<*>?) - Optional - The custom receiver class for background messages. - **channel** (String?) - Optional - Notification channel ID for library-displayed pushes. - **enableLogger** (Boolean) - Optional - Enables local logging for debugging. - **askPermissions** (Boolean) - Optional - Automatically requests notification and background permissions on startup. - **applicationId** (String?) - Optional - The application ID from the Pushed dashboard. ``` -------------------------------- ### Configure APNS Only Mode Source: https://multipushed.ru/docs/iOS_library Initialize or switch to a classic mode using only APNS. ```swift // Через setup: PushedMessagingiOSLibrary.setup(self, useAPNS: true, enableWebSocket: false) // Или переключить на лету: PushedMessagingiOSLibrary.enableAPNS() PushedMessagingiOSLibrary.disableWebSocket() ``` -------------------------------- ### pushedService.askPermissions() Source: https://multipushed.ru/docs/androidlibrary Manually requests necessary permissions for notifications and background work. ```APIDOC ## pushedService.askPermissions(askNotification, askBackgroundWork) ### Description Manually triggers permission requests if automatic requests were disabled during initialization. ### Parameters - **askNotification** (Boolean) - Required - Requests permission to display notifications. - **askBackgroundWork** (Boolean) - Required - Requests permission to ignore battery optimizations. ``` -------------------------------- ### Настройка Main.cpp для Flutter Aurora Source: https://multipushed.ru/docs/auroralibrary Инициализирует Flutter-приложение с поддержкой Qt и управлением GUI через аргументы командной строки. ```cpp #include #include #include #include #include #include #include "generated_plugin_registrant.h" int main(int argc, char* argv[]) { bool noGui = false; for (int i = 1; i < argc; ++i) { if (qstrcmp(argv[i], "--no-gui") == 0) { noGui = true; break; } } aurora::Initialize(argc, argv); aurora::EnableQtCompatibility(); aurora::RegisterPlugins(); FlutterAuroraLaunchOptions options; FlutterAuroraLaunchOptionsInitDefault(&options, sizeof(options)); options.gui_type = noGui ? FlutterAuroraGuiForceDisabled : FlutterAuroraGuiForceEnabled; qDebug() << "Launching Flutter" << (noGui ? "headless" : "with GUI"); FlutterAuroraLaunch(&options); return 0; } ``` -------------------------------- ### Create a MessageReceiver Source: https://multipushed.ru/docs/androidlibrary Implement the MessageReceiver class to handle background messages received by the application. ```kotlin class MyMessageReceiver : MessageReceiver() { override fun onBackgroundMessage(context: Context?, message: JSONObject) { Log.d("MyMessageReceiver", "Получено фоновое сообщение: $message") } } ``` -------------------------------- ### Запрос статуса сообщения по ID Source: https://multipushed.ru/docs/API/statuswebpush Используйте этот запрос для получения детальной информации о конкретном пуш-сообщении по его идентификатору. ```bash curl -v -X POST https://pub.multipushed.ru/v2/messages/ -H "Content-Type: application/json" -H "Authorization: Bearer " ``` -------------------------------- ### API Endpoint для управления статусом токена Source: https://multipushed.ru/docs/API/managingtokensstatuses Базовый URL для выполнения POST-запросов по управлению статусами. ```http POST api.pushed.ru/v2/management/client-token-status ``` -------------------------------- ### POST /v2/broadcast-publish Source: https://multipushed.ru/docs/API/broadcast Mass distribution of push notifications to devices. ```APIDOC ## POST https://pub.multipushed.ru/v2/broadcast-publish ### Description Mass distribution of push notifications to devices. ### Method POST ### Endpoint https://pub.multipushed.ru/v2/broadcast-publish ### Parameters #### Request Body - **ttl** (integer) - Optional - Time to live in seconds (default 24 hours) - **payload** (string) - Required - Message body - **cascadeToSms** (boolean) - Optional - Enable SMS cascade (default true) - **sms.body** (string) - Optional - SMS message body - **groupId** (string) - Optional - Group identifier - **geoLocationInfo** (object) - Optional - Region for delivery (ISO 3166) - **apns** (object) - Optional - APNs specific settings ### Request Example { "payload": "My payload", "cascadeToSms": true, "sms": { "body": "Sms payload" } } ### Response #### Success Response (200) - **success** (boolean) - Result of the request - **errCode** (integer/null) - Error code if applicable - **message** (string/null) - Error description if applicable - **model** (string/null) - Broadcast task ID #### Response Example { "success": true, "errCode": null, "message": null, "model": "12345" } ``` -------------------------------- ### Verify Device Token Registration Source: https://multipushed.ru/docs/flutterplugin Print the device token to verify successful registration for push notifications. ```dart # Проверка регистрации устройства print("Токен: ${FlutterPushedMessaging.token}"); ``` -------------------------------- ### Log Background Messages Source: https://multipushed.ru/docs/flutterplugin Implement a background handler with the required entry-point annotation to debug background message delivery. ```dart // Добавьте логирование в фоновый обработчик @pragma('vm:entry-point') Future backgroundMessage(Map message) async { print("ФОНОВОЕ: $message"); } ```