Ana içeriğe atla

Genel bakış

Notification Service Extension’lar, kullanıcıya gösterilmeden önce push bildirimlerini kesintiye uğratmanıza ve değiştirmenize olanak tanır. Bu şunları sağlar:
  • Arka plan veri işleme
  • Özel stiller (renkler, simgeler, titreşim)
  • Zengin medya ekleri (resimler, videolar)
  • Onaylanmış teslimat/analitik
  • Eylem düğmesi seçenekleri
OneSignal’den gönderilen push bildirimlerinizdeki verilere OSNotification sınıfı aracılığıyla erişebilirsiniz

Android Notification Service Extension

Kullanıcıya gösterilmeden önce bildirimi işlemenize olanak tanır. Yaygın kullanım durumları şunlardır:
  • Bir bildirim göstererek veya göstermeden arka planda veri alın.
  • Özel vurgu rengi, titreşim deseni veya mevcut diğer NotificationCompat seçenekleri gibi istemci tarafı uygulama mantığına bağlı olarak belirli bildirim ayarlarını geçersiz kılın.
Daha fazla ayrıntı için Android’in NotificationCompat seçenekleri hakkındaki belgelerine bakın.

1. Service Extension için bir sınıf oluşturun

INotificationServiceExtension’ı genişleten bir sınıf oluşturun ve onNotificationReceived yöntemini uygulayın. onNotificationReceived yöntemi parametresi, INotificationReceivedEvent türünde event’tir.
package your.package.name

import androidx.annotation.Keep;
import com.onesignal.notifications.IActionButton;
import com.onesignal.notifications.IDisplayableMutableNotification;
import com.onesignal.notifications.INotificationReceivedEvent;
import com.onesignal.notifications.INotificationServiceExtension;

@Keep // Keep is required to prevent minification from renaming or removing your class
public class NotificationServiceExtension implements INotificationServiceExtension {

     @Override
     public void onNotificationReceived(INotificationReceivedEvent event) {
        IDisplayableMutableNotification notification = event.getNotification();

        if (notification.getActionButtons() != null) {
           for (IActionButton button : notification.getActionButtons()) {
              // you can modify your action buttons here
           }
        }

     /* Add customizations here. See examples below for additional methods to modify the notification*/
     }
}

2. Örnek kullanım durumları

Aşağıdakiler, yukarıdaki şablon Notification Service Extension sınıfında uygulayabileceğiniz yaygın örneklerdir.
  • Bildirimin görüntülenmesini önleme
  • Özel alan ekleme
  • Bildirim rengini ve simgesini değiştirme
event.preventDefault();

//Do some async work, then decide to show or dismiss
new Thread(() -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ignored) {}

    //Manually show the notification
    event.getNotification().display();
}).start();

3. Service Extension’ı AndroidManifest.xml’inize ekleyin

Sınıf adını ve değerini AndroidManifest.xml dosyasında application etiketi içinde meta-data olarak ekleyin. Herhangi bir “kullanılmayan” uyarısını yoksayın.
XML
<application>
  <!-- Keep android:name as shown, set android:value toyour class fully name spaced-->
  <meta-data
    android:name="com.onesignal.NotificationServiceExtension"
    android:value="com.onesignal.example.NotificationServiceExtension" />
</application>

iOS Notification Service Extension

UNNotificationServiceExtension, push bildirimlerinin kullanıcıya gösterilmeden önce içeriğini değiştirmenize olanak tanır ve şunlar gibi diğer önemli özellikler için gereklidir: Uygulamanız için Mobile SDK kurulum talimatlarımızı izlediyseniz muhtemelen bunu zaten kurmuşsunuzdur, ancak bu bölüm OneSignal bildirim yükü verilerine nasıl erişeceğinizi ve karşılaşabileceğiniz sorunları nasıl gidereceğinizi açıklayacaktır.

iOS push yükünü alma

Mobile SDK kurulum’u takip ettiğinizde, OneSignalNotificationServiceExtension’a kod ekleme bölümüne geleceksiniz. Bu kodda, OneSignalExtension.didReceiveNotificationExtensionRequest yöntemi vardır. Kullanıcıya gösterilmeden önce bildirimin bestAttemptContent’ini uygulamaya ilettiğimiz yer burasıdır. Bu yöntem çağrılmadan önce, bildirim yükünü alabilir ve (isterseniz) kullanıcıya gösterilmeden önce güncelleyebilirsiniz. Bu örnekte, aşağıdaki verilerle bir bildirim gönderiyoruz:
JSON
{
  "app_id": "YOUR_APP_ID",
  "target_channel": "push",
  "headings": {"en": "The message title"},
  "contents": {"en": "The message contents"},
  "data":{
    "additional_data_key_1":"value_1",
    "additional_data_key_2":"value_2"
    },
  "include_subscription_ids": ["SUBSCRIPTION_ID_1"]
}
Bu ek data’ya OneSignalNotificationServiceExtension içinde a parametresini kullanan custom nesnesi aracılığıyla erişebiliriz.
// Check if `bestAttemptContent` exists
if let bestAttemptContent = bestAttemptContent {

    // Try to retrieve the "custom" data from the notification payload
    if let customData = bestAttemptContent.userInfo["custom"] as? [String: Any],
       let additionalData = customData["a"] as? [String: Any] {

        // Convert the `additionalData` dictionary to a JSON string for logging
        if let jsonData = try? JSONSerialization.data(withJSONObject: additionalData, options: .prettyPrinted),
           let jsonString = String(data: jsonData, encoding: .utf8) {
            // Successfully converted to JSON; log the formatted JSON string
            print("The additionalData dictionary in JSON format:\n\(jsonString)")
        } else {
            // Failed to convert the `additionalData` dictionary to JSON
            print("Failed to convert additionalData to JSON format.")
        }
    }

    // Try to retrieve the "aps" data from the notification payload
    if let messageData = bestAttemptContent.userInfo["aps"] as? [String: Any],
       let apsData = messageData["alert"] as? [String: Any],
       let body = apsData["body"] as? String,  // Extract the "body" of the alert
       let title = apsData["title"] as? String {  // Extract the "title" of the alert
        // Successfully retrieved the body and title; log the values
        print("The message contents is: \(body), message headings is: \(title)")
    } else {
        // Failed to retrieve the "aps" data or its contents
        print("Unable to retrieve apsData")
    }

    // Pass the notification to OneSignal for further processing
    OneSignalExtension.didReceiveNotificationExtensionRequest(self.receivedRequest,
                                                              with: bestAttemptContent,
                                                              withContentHandler: self.contentHandler)
}
Örnek konsol çıktısı:
The additionalData dictionary in JSON format:
{
  "additional_data_key_1" : "value_1",
  "additional_data_key_2" : "value_2"
}
The message contents is: The message contents, message headings is: The message title

iOS Notification Service Extension’da sorun giderme

Bu kılavuz, iOS mobil uygulamalarında gösterilmeyen Resimler, Eylem Düğmeleri veya Onaylanmış Teslimatlarla ilgili sorunları gidermek içindir. Xcode Ayarlarınızı kontrol edin General > Targets içinde ana uygulama hedefiniizin ve OneSignalNotificationServiceExtension hedefinin aynı ve doğru olduğundan emin olun:
  • Supported Destinations
  • Minimum Deployment (iOS 14.5 veya üstü)
Cocoapods kullanıyorsanız, derleme hatalarını önlemek için bunların Podfile’daki ana hedefinizle eşleştiğinden emin olun.

Xcode'da Örnek Ana Uygulama Hedefi

Xcode'da Örnek OneSignalNotificationServiceExtension Hedefi

OneSignalNotificationServiceExtension > Info sekmesinde devam ederek, NSExtension anahtarını genişletin. Şunları gördüğünüzden emin olun:
XML
 <dict>
   <key>NSExtensionPointIdentifier</key>
   <string>com.apple.usernotifications.service</string>
   <key>NSExtensionPrincipalClass</key>
   <string>$(PRODUCT_MODULE_NAME).NotificationService</string>
 </dict>
Örnek:

Info sekmesinde Örnek NSExtension anahtarı

Objective-C kullanıyorsanız, $(PRODUCT_MODULE_NAME).NotificationService yerine NotificationService kullanın.
“Copy only when installing“‘i kapatın Ana uygulama hedefi > Build Phases > Embed App Extensions’ı seçin. “Copy only when installing”in işaretlenmediğinden emin olun. Eğer işaretliyse işareti kaldırın:

Ana uygulama hedefi derleme aşaması ayarları

iOS Notification Service Extension’da hata ayıklama

Notification Service Extension’ın doğru şekilde kurulduğunu doğrulamak için şu adımları izleyin.

1. OneSignalNotificationServiceExtension kodunu güncelleyin

NotificationService.m veya NotificationService.swift’i açın ve tüm dosya içeriğini aşağıdaki kodla değiştirin. (Kod, orijinal kurulum kodumuzla aynıdır, sadece bazı ek günlükler eklenmiştir. YOUR_BUNDLE_ID’yi gerçek Bundle ID’nizle değiştirdiğinizden emin olun.
import UserNotifications
import OneSignalExtension
import os.log

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var receivedRequest: UNNotificationRequest!
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.receivedRequest = request
        self.contentHandler = contentHandler
        self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

        let userInfo = request.content.userInfo
        let custom = userInfo["custom"]
        print("Running NotificationServiceExtension: userInfo = \(userInfo.description)")
        print("Running NotificationServiceExtension: custom = \(custom.debugDescription)")
        //debug log types need to be enabled in Console > Action > Include Debug Messages
        //Replace YOUR_BUNDLE_ID with your actual Bundle ID
        os_log("%{public}@", log: OSLog(subsystem: "YOUR_BUNDLE_ID", category: "OneSignalNotificationServiceExtension"), type: OSLogType.debug, userInfo.debugDescription)

        if let bestAttemptContent = bestAttemptContent {
            /* DEBUGGING: Uncomment the 2 lines below to check this extension is executing
                          Note, this extension only runs when mutable-content is set
                          Setting an attachment or action buttons automatically adds this */
            print("Running NotificationServiceExtension")
            bestAttemptContent.body = "[Modified] " + bestAttemptContent.body

            OneSignalExtension.didReceiveNotificationExtensionRequest(self.receivedRequest, with: bestAttemptContent, withContentHandler: self.contentHandler)
        }
    }

    override func serviceExtensionTimeWillExpire() {
        // Called just before the extension will be terminated by the system.
        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            OneSignalExtension.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent)
            contentHandler(bestAttemptContent)
        }
    }

}

2. Aktif Şemanızı değiştirin

Aktif Şemanızı OneSignalNotificationServiceExtension’a ayarlayın.

Xcode aktif şema seçimi

3. Projeyi derleyin ve çalıştırın

Projeyi Xcode’da gerçek bir cihazda derleyin ve çalıştırın.

4. Konsolu açın

Xcode’da Window > Devices and Simulators’ı seçin.

Xcode Devices and Simulators penceresi

Cihazınızın bağlı olduğunu görmelisiniz. Open Console’u seçin.

Cihaz konsolu erişim düğmesi

5. Konsolu kontrol edin

Konsolda:
  • Action > Include Debug Messages’ı seçin
  • CATEGORY olarak OneSignalNotificationServiceExtension araması yapın
  • Start’ı seçin

Konsol hata ayıklama yapılandırması

Bu cihaza bir mesaj içeren bir bildirim gönderin (Create message API’sinden gönderiyorsanız contents özelliğini kullanın). Bu örnekte, yük şudur:
cURL
  //Replace with your own app data:
  //YOUR_API_KEY, YOUR_APP_ID, SUBSCRIPTION_ID_1

curl --request POST \
 --url 'https://api.onesignal.com/notifications' \
 --header 'Authorization: Key YOUR_API_KEY' \
 --header 'accept: application/json' \
 --header 'content-type: application/json' \
 --data '
{
"app_id": "YOUR_APP_ID",
"target_channel": "push",
"headings": {"en": "The message title"},
"contents": {"en": "The message contents"},
"data":{"additional_data_key_1":"value_1","additional_data_key_2":"value_2"},
"include_subscription_ids": [
"SUBSCRIPTION_ID_1"
]
}'
Uygulama çalışırken ve çalışmıyorken günlüğe kaydedilmiş bir mesaj görmelisiniz.

Konsol hata ayıklama çıktısı örneği

Bir mesaj görmüyorsanız, OneSignal’i uygulamanızdan kaldırın ve OneSignal’i doğru şekilde kurduğunuzu doğrulamak için Mobile SDK Setup kılavuzumuzu tekrar takip edin.