Apple platformlarında birden çok cihaza ileti gönderme

Bir mesajı birden çok cihaza hedeflemek için şunu kullanın: Konu mesajları. Bu özelliği kullanarak Belirli bir konuda kaydolan birden çok cihaza mesaj gönderebilirsiniz.

Bu eğitim, Admin SDK veya REST API ve bunları alıp ele alma sürecini ekleyebilirsiniz. Bu sayfada, kurulumdan, pazarlamaya kadar, bunu başarmak için atmanız gereken tüm adımlar Bu nedenle, eğer şu anda daha önce tamamlamış olduğunuz adımlara FCM için Apple istemci uygulaması kurma veya İlk Mesajınızı Gönderme adımlarını uygulayın.

Firebase'i Apple projenize ekleyin

Bu bölümde, daha önce etkinleştirdiyseniz tamamlamış olabileceğiniz görevler ele alınmaktadır diğer Firebase özelliklerini kullanabilirsiniz. Özellikle FCM için: gerek APN kimlik doğrulama anahtarınızı yükleyin ve uzaktan bildirim almak için kaydolun.

Ön koşullar

  • Aşağıdakileri yükleyin:

    • Xcode 14.1 veya sonraki sürümler
  • Projenizin şu gereklilikleri karşıladığından emin olun:

    • Projeniz şu platform sürümlerini veya sonraki sürümleri hedeflemelidir:
      • iOS 11
      • macOS 10.13
      • tvOS 12
      • watchOS 6
  • Uygulamanızı çalıştırmak için fiziksel bir Apple cihaz kurun, ve şu görevleri tamamlayın:

    • için bir Apple Anında Bildirim Kimlik Doğrulama Anahtarı edinin Apple Geliştirici hesabı
    • XCode'daki Push Bildirimleri'ni Uygulama > Özellikler.

Xcode projeniz yoksa ve bir Firebase'i denemek istiyorsanız hızlı başlangıç örneklerimizden birini indirebilirsiniz.

Firebase projesi oluşturma

Firebase'i Apple uygulamanıza ekleyebilmek için öncelikle bir Firebase oluşturmanız gerekir projenize bağlanabilirsiniz. Ziyaret edin: Şu konular hakkında daha fazla bilgi edinmek için Firebase Projelerini Anlama: Firebase projeleri.

Uygulamanızı Firebase'e kaydedin

Firebase'i Apple uygulamanızda kullanmak için uygulamanızı Firebase projesi. Uygulamanızı kaydetme işlemi genellikle "ekleme" olarak adlandırılır uygulamanızı belirler.

  1. Firebase konsoluna gidin.

  2. Projeye genel bakış sayfasının ortasındaki iOS+ simgesini tıklayın. kurulum iş akışını başlatın.

    Firebase projenize daha önce uygulama eklediyseniz Uygulama ekle'yi tıklayın tıklayın.

  3. Uygulamanızın paket kimliğini paket kimliği alanına girin.

    ziyaret edin.
  4. (İsteğe bağlı) Diğer uygulama bilgilerini girin: Uygulama takma adı ve App Store kimliği.

  5. Uygulamayı kaydet'i tıklayın.

Firebase yapılandırma dosyası ekleme

  1. Firebase Apple'ınızı edinmek için GoogleService-Info.plist dosyasını indir'i tıklayın platformların yapılandırma dosyasına (GoogleService-Info.plist) bakın.

  2. Yapılandırma dosyanızı Xcode projenizin köküne taşıyın. İstenirse Yapılandırma dosyasını tüm hedeflere eklemeyi seçin.

Projenizde birden fazla paket kimliği varsa her paketi ilişkilendirmeniz gerekir. Firebase konsolunda kayıtlı bir uygulamayla kimlik doğrulaması yaparak her uygulamanın kendine ait GoogleService-Info.plist dosyası vardır.

Firebase SDK'larını uygulamanıza ekleyin

Firebase bağımlılıklarını yükleyip yönetmek için Swift Package Manager'ı kullanın.

  1. Xcode'da, uygulama projeniz açıkken Dosya > Paket Ekle'yi tıklayın.
  2. İstendiğinde Firebase Apple platformlar SDK deposunu ekleyin:
  3.   https://github.com/firebase/firebase-ios-sdk.git
    .
  4. Firebase Cloud Messaging kitaplığını seçin.
  5. -ObjC işaretini, hedefinizin derleme ayarlarındaki Diğer Bağlayıcı İşaretleri bölümüne ekleyin.
  6. Firebase Cloud Messaging ile optimum bir deneyim için şunları yapmanızı öneririz: Google Analytics'i etkinleştirme Firebase projenize ekleyin ve uygulamanıza Google Analytics için Firebase SDK'sını ekleyin. Şunları yapabilirsiniz: IDFA koleksiyonu olmayan veya IDFA koleksiyonu olan kitaplığı seçin.
  7. İşlemi tamamladığınızda, Xcode otomatik olarak arka planda tutmalarını sağlar.

APNs kimlik doğrulama anahtarınızı yükleyin

APNs kimlik doğrulama anahtarınızı Firebase'e yükleyin. Halihazırda bir APNs kimlik doğrulama anahtarınız yoksa Apple Geliştirici Üye Merkezi.

  1. Firebase konsolunda projenizin içinde, dişli simgesi, seçin Proje Ayarları'nı tıklayın ve ardından Cloud Messaging sekmesi.

  2. iOS uygulaması yapılandırması bölümündeki APN kimlik doğrulama anahtarı'nda, Yükle'yi tıklayın. düğmesini tıklayın.

  3. Anahtarınızı kaydettiğiniz konuma gidin, anahtarı seçin ve . Anahtarın anahtar kimliğini ekleyin ( Apple Developer Member Center) oturum açın Yükle.

Uygulamanızda Firebase'i başlatın

Firebase başlatma kodunu uygulamanıza eklemeniz gerekir. İçe aktarma inceleyin ve paylaşılan bir örneği aşağıda gösterildiği gibi yapılandırın:

  1. FirebaseCore modülünü UIApplicationDelegate ve diğer Yetki verdiğiniz uygulamanın kullandığı Firebase modülleri. Örneğin, Cloud Firestore ve Authentication'ı kullanmak için:

    Hızlı Kullanıcı Arayüzü

    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Swift

    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Objective-C

    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  2. Şunu yapılandır: FirebaseApp paylaşılan örneğinizin application(_:didFinishLaunchingWithOptions:) yöntemi:

    Hızlı Kullanıcı Arayüzü

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Swift

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  3. SwiftUI kullanıyorsanız bir uygulama temsilcisi oluşturup bunu eklemeniz gerekir UIApplicationDelegateAdaptor veyaApp NSApplicationDelegateAdaptor. Uygulama yetkilendirmesi kaydırmayı da devre dışı bırakmanız gerekir. Örneğin, daha fazla bilgi için SwiftUI talimatlarına bakın.

    Hızlı Kullanıcı Arayüzü

    @main
    struct YourApp: App {
      // register app delegate for Firebase setup
      @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
      var body: some Scene {
        WindowGroup {
          NavigationView {
            ContentView()
          }
        }
      }
    }
          

Uzaktan bildirimlere kaydol

Başlangıçta veya uygulama akışınızda istenilen noktada uygulamanızı uzaktan bildirimlere kaydetme. Telefonla arama Gösterilen registerForRemoteNotifications:

Swift


UNUserNotificationCenter.current().delegate = self

let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
  options: authOptions,
  completionHandler: { _, _ in }
)

application.registerForRemoteNotifications()

Objective-C


[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
    UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
    requestAuthorizationWithOptions:authOptions
    completionHandler:^(BOOL granted, NSError * _Nullable error) {
      // ...
    }];

[application registerForRemoteNotifications];

İstemci uygulamasının bir konuya abone olmasını sağlama

İstemci uygulamaları mevcut herhangi bir konuya abone olabilir veya yeni bir konu oluşturabilir konu. Bir istemci uygulaması yeni bir konu adına abone olduğunda ( Firebase projeniz için zaten mevcut değilse) bu ada sahip yeni bir konu oluşturabilirsiniz. Böylece tüm müşteriler daha sonra bu hizmete abone olabilir.

Bir konuya abone olmak için abonelik yöntemini çağırın (FCM, iş parçacığı açısından güvenli değildir). Abonelik isteği başlangıçta başarısız olursa FCM otomatik olarak yeniden dener. Aboneliğin tamamlanamadığı durumlarda, abonelik, yakalayabileceğiniz bir hata aşağıdaki gibi bir tamamlama işleyicide:

Swift

Messaging.messaging().subscribe(toTopic: "weather") { error in
  print("Subscribed to weather topic")
}

Objective-C

[[FIRMessaging messaging] subscribeToTopic:@"weather"
                                completion:^(NSError * _Nullable error) {
  NSLog(@"Subscribed to weather topic");
}];

Bu çağrı, FCM arka ucuna eşzamansız istek gönderir ve istemciyi açıklayacağım. subscribeToTopic:topic numaralı telefonu aramadan önce istemci uygulama örneği, geri arama didReceiveRegistrationToken.

Uygulama her başlatıldığında, FCM, istenen tüm konulara abone olunmasını sağlar. Alıcı: e-posta listesinden çık, unsubscribeFromTopic:topic numaralı telefonu ara, ve FCM, arka planda bu konunun aboneliğinden çıkar.

Konu mesajlarını alma ve işleme

FCM, konu mesajlarını diğer aşağı akışla aynı şekilde sunar mesaj.

application(_:didReceiveRemoteNotification:fetchCompletionHandler:) uygulayın gösterildiği gibi:

Swift

func application(_ application: UIApplication,
                 didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async
  -> UIBackgroundFetchResult {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // Messaging.messaging().appDidReceiveMessage(userInfo)

  // Print message ID.
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }

  // Print full message.
  print(userInfo)

  return UIBackgroundFetchResult.newData
}

Objective-C

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // ...

  // Print full message.
  NSLog(@"%@", userInfo);

  completionHandler(UIBackgroundFetchResultNewData);
}

Gönderme istekleri oluşturma

Bir konu oluşturduktan sonra, istemci uygulaması örneklerini müşteri tarafında veya müşteri tarafında sunucu API'sine sahipseniz, konu. FCM için gönderme isteklerini ilk kez oluşturuyorsanız kılavuzu inceleyin sunucu ortamınıza ve FCM'ye önemli arka plan ve kurulum bilgilerini sağlar.

Arka uçtaki gönderme mantığınızda istediğiniz konu adını belirtin. gösterildiği gibi:

Node.js

// The topic name can be optionally prefixed with "/topics/".
const topic = 'highScores';

const message = {
  data: {
    score: '850',
    time: '2:45'
  },
  topic: topic
};

// Send a message to devices subscribed to the provided topic.
getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Java

// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";

// See documentation on defining a message payload.
Message message = Message.builder()
    .putData("score", "850")
    .putData("time", "2:45")
    .setTopic(topic)
    .build();

// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);

Python

# The topic name can be optionally prefixed with "/topics/".
topic = 'highScores'

# See documentation on defining a message payload.
message = messaging.Message(
    data={
        'score': '850',
        'time': '2:45',
    },
    topic=topic,
)

# Send a message to the devices subscribed to the provided topic.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

Go

// The topic name can be optionally prefixed with "/topics/".
topic := "highScores"

// See documentation on defining a message payload.
message := &messaging.Message{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Topic: topic,
}

// Send a message to the devices subscribed to the provided topic.
response, err := client.Send(ctx, message)
if err != nil {
	log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)

C#

// The topic name can be optionally prefixed with "/topics/".
var topic = "highScores";

// See documentation on defining a message payload.
var message = new Message()
{
    Data = new Dictionary<string, string>()
    {
        { "score", "850" },
        { "time", "2:45" },
    },
    Topic = topic,
};

// Send a message to the devices subscribed to the provided topic.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
    "topic" : "foo-bar",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message"
      }
   }
}

cURL komutu:

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
  "message": {
    "topic" : "foo-bar",
    "notification": {
      "body": "This is a Firebase Cloud Messaging Topic Message!",
      "title": "FCM Message"
    }
  }
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Konulardan oluşan bir kombinasyona ileti göndermek için: bir koşul belirtin. Bu, konuları ele alalım. Örneğin, aşağıdaki koşul iletileri TopicA ve TopicB ya da TopicC aboneliklerine abone olan cihazlar:

"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"

FCM önce parantez içindeki koşulları değerlendirir, ardından tıklayın. Yukarıdaki ifadede, bir kullanıcı mesajı almamasını sağlayabilirsiniz. Benzer şekilde, TopicA için abone ol düğmesi, mesajı almıyor. Bu kombinasyonlar alın:

  • TopicA ve TopicB
  • TopicA ve TopicC

Koşullu ifadenize en fazla beş konu ekleyebilirsiniz.

Bir koşula göndermek için:

Node.js

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
const condition = '\'stock-GOOG\' in topics || \'industry-tech\' in topics';

// See documentation on defining a message payload.
const message = {
  notification: {
    title: '$FooCorp up 1.43% on the day',
    body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  condition: condition
};

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Java

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
String condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

// See documentation on defining a message payload.
Message message = Message.builder()
    .setNotification(Notification.builder()
        .setTitle("$GOOG up 1.43% on the day")
        .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
        .build())
    .setCondition(condition)
    .build();

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);

Python

# Define a condition which will send to devices which are subscribed
# to either the Google stock or the tech industry topics.
condition = "'stock-GOOG' in topics || 'industry-tech' in topics"

# See documentation on defining a message payload.
message = messaging.Message(
    notification=messaging.Notification(
        title='$GOOG up 1.43% on the day',
        body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
    ),
    condition=condition,
)

# Send a message to devices subscribed to the combination of topics
# specified by the provided condition.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

Go

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
condition := "'stock-GOOG' in topics || 'industry-tech' in topics"

// See documentation on defining a message payload.
message := &messaging.Message{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Condition: condition,
}

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
response, err := client.Send(ctx, message)
if err != nil {
	log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)

C#

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

// See documentation on defining a message payload.
var message = new Message()
{
    Notification = new Notification()
    {
        Title = "$GOOG up 1.43% on the day",
        Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
    },
    Condition = condition,
};

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
   "message":{
    "condition": "'dogs' in topics || 'cats' in topics",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message",
    }
  }
}

cURL komutu:

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
  "notification": {
    "title": "FCM Message",
    "body": "This is a Firebase Cloud Messaging Topic Message!",
  },
  "condition": "'dogs' in topics || 'cats' in topics"
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Sonraki adımlar

  • Sunucunuzu kullanarak istemci uygulaması örneklerini konulara abone yapabilir ve diğer yönetim görevlerini tamamlamanıza yardımcı olur. Görüntüleyin Sunucudaki konu aboneliklerini yönetin.