Ana içeriğe atla
Notification Service Extension’lar, kullanıcıya gösterilmeden önce push bildirimlerini kesintiye uğratmanıza ve değiştirmenize olanak tanır. Bu; arka plan veri işleme, özel stiller, zengin medya ekleri, onaylanmış teslimat ve eylem düğmesi seçeneklerini etkinleştirir.
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.

Adım 1: Servis uzantısı için bir sınıf oluşturun

INotificationServiceExtension’ı uygulayan 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*/
     }
}

@Keep anotasyonu, ProGuard veya R8’in minifikasyon sırasında sınıfınızı yeniden adlandırmasını veya kaldırmasını önlemek için gereklidir.

Adım 2: Bildirimi özelleştirin

Aşağıdaki örnekler, Notification Service Extension sınıfında uygulayabileceğiniz yaygın özelleştirmeleri göstermektedir.
Bildirimin görüntülenmesini engellemek için event.preventDefault() kullanın. Daha sonra görüntülemek için event.getNotification().display() çağırabilir ya da sessizce atmak için hiç çağırmayabilirsiniz.
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();
event.preventDefault() çağrılıp display() hiç çağrılmazsa bildirim sessizce atılır. Daha fazla bilgi için Yinelenen bildirimler sayfasına bakın.

Adım 3: Servis uzantısını 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>
  <meta-data
    android:name="com.onesignal.NotificationServiceExtension"
    android:value="com.onesignal.example.NotificationServiceExtension" />
</application>
com.onesignal.example.NotificationServiceExtension yerine sınıfınızın tam nitelikli adını yazın.

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

didReceive(_:withContentHandler:) override’ı, bestAttemptContent’i görüntülenmeden önce OneSignal’e ileten OneSignalExtension.didReceiveNotificationExtensionRequest’i çağırır. Bu yöntem çağrılmadan önce bestAttemptContent’i okuyabilir veya değiştirebilirsiniz. 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 userInfo’nun custom sözlüğündeki a anahtarı aracılığıyla erişin:
if let bestAttemptContent = bestAttemptContent {

    if let customData = bestAttemptContent.userInfo["custom"] as? [String: Any],
       let additionalData = customData["a"] as? [String: Any] {

        if let jsonData = try? JSONSerialization.data(withJSONObject: additionalData, options: .prettyPrinted),
           let jsonString = String(data: jsonData, encoding: .utf8) {
            print("The additionalData dictionary in JSON format:\n\(jsonString)")
        } else {
            print("Failed to convert additionalData to JSON format.")
        }
    }

    if let messageData = bestAttemptContent.userInfo["aps"] as? [String: Any],
       let apsData = messageData["alert"] as? [String: Any],
       let body = apsData["body"] as? String,
       let title = apsData["title"] as? String {
        print("The message contents is: \(body), message headings is: \(title)")
    } else {
        print("Unable to retrieve apsData")
    }

    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 General tab showing Supported Destinations and Minimum Deployment for the main app target
Xcode General tab showing Supported Destinations and Minimum Deployment for the notification service extension target
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:
Xcode Info tab showing the NSExtension dictionary with NSExtensionPointIdentifier and NSExtensionPrincipalClass keys
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:
Xcode Build Phases tab showing Embed App Extensions with Copy only when installing unchecked

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. Bu, uzantının çalışıp çalışmadığını doğrulamaya yardımcı olmak için günlükleme ekler. YOUR_BUNDLE_ID’yi gerçek Bundle ID’nizle değiştirin.
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)")
        os_log("%{public}@", log: OSLog(subsystem: "YOUR_BUNDLE_ID", category: "OneSignalNotificationServiceExtension"), type: OSLogType.debug, userInfo.debugDescription)

        if let bestAttemptContent = bestAttemptContent {
            print("Running NotificationServiceExtension")
            bestAttemptContent.body = "[Modified] " + bestAttemptContent.body

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

    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            OneSignalExtension.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent)
            contentHandler(bestAttemptContent)
        }
    }

}

Hata ayıklama günlük türlerinin Konsol’da Action > Include Debug Messages aracılığıyla etkinleştirilmesi gerekir.

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

Aktif Şemanızı OneSignalNotificationServiceExtension’a ayarlayın.
Xcode toolbar showing the active scheme dropdown set to OneSignalNotificationServiceExtension

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 menu showing the Window dropdown with Devices and Simulators selected
Cihazınızın bağlı olduğunu görmelisiniz. Open Console’u seçin.
Xcode Devices window showing the Open Console button for a connected device

5. Konsolu kontrol edin

Konsolda:
  1. Action > Include Debug Messages’ı seçin
  2. CATEGORY olarak OneSignalNotificationServiceExtension araması yapın
  3. Start’ı seçin
macOS Console app showing the category filter and Start button for debugging the notification service extension
Bu cihaza bir mesaj içeren bir bildirim gönderin (Bildirim oluştur API’sinden gönderiyorsanız contents özelliğini kullanın). Bu örnekte, yük şudur:
cURL
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.
macOS Console app showing debug log output from the OneSignalNotificationServiceExtension
Bir mesaj görmüyorsanız, OneSignal’i uygulamanızdan kaldırın ve entegrasyonu doğrulamak için Mobile SDK Setup kılavuzunu tekrar takip edin.

SSS

iOS’ta bildirim servis uzantım neden çalışmıyor? Uzantı yalnızca bildirim yükünde mutable-content ayarlandığında çalışır. OneSignal, ekler veya eylem düğmeleri içeren bildirimler için bunu otomatik olarak ayarlar. Xcode ayarlarınızın sorun giderme bölümüyle eşleştiğini doğrulayın. Android’de bir bildirimin görüntülenmesini engelleyebilir miyim? Evet. Görüntülemeyi engellemek için event.preventDefault() çağırın. Daha sonra görüntülemek için event.getNotification().display() çağırın ya da sessizce atmak için hiç çağırmayın. Daha fazla bilgi için Yinelenen bildirimler sayfasına bakın. Android’de @Keep anotasyonuna ihtiyacım var mı? Evet. ProGuard veya R8’in minifikasyon sırasında INotificationServiceExtension’ı uygulayan sınıfınızı yeniden adlandırmasını veya kaldırmasını önler.

İlgili sayfalar

Mobile SDK Kurulumu

iOS ve Android için OneSignal SDK’yı yükleyin ve yapılandırın.

Resimler ve zengin medya

Push bildirimlerine resim, GIF ve video ekleyin.

Onaylanmış teslimat

Cihazlara onaylanmış bildirim teslimatını takip edin.

Yinelenen bildirimler

Tüm platformlarda yinelenen push bildirimlerini giderin.