Apple platformlarında birden fazla cihaza mesaj gönderin

Bir mesajı birden fazla cihaza hedeflemek için Konu mesajlaşmayı kullanın. Bu özellik, belirli bir konuyu seçen birden fazla cihaza mesaj göndermenize olanak tanır.

Bu eğitim, FCM için Admin SDK veya REST API'yi kullanarak uygulama sunucunuzdan konu mesajlarının gönderilmesine ve bunların bir Apple uygulamasında alınıp işlenmesine odaklanmaktadır. Bu sayfa, kurulumdan doğrulamaya kadar bunu başarmaya yönelik tüm adımları listeler; dolayısıyla, FCM için bir Apple istemci uygulaması ayarladıysanız veya İlk Mesajınızı Gönderme adımlarını uyguladıysanız, halihazırda tamamlamış olduğunuz adımları kapsayabilir.

Firebase'i Apple projenize ekleyin

Bu bölüm, uygulamanız için diğer Firebase özelliklerini zaten etkinleştirdiyseniz tamamlamış olabileceğiniz görevleri kapsar. Özellikle FCM için APN kimlik doğrulama anahtarınızı yüklemeniz ve uzaktan bildirimlere kaydolmanız gerekir.

Önkoşullar

  • Aşağıdakileri yükleyin:

    • Xcode 14.1 veya üzeri
  • Projenizin şu gereksinimleri karşıladığından emin olun:

    • Projeniz şu platform sürümlerini veya sonraki sürümlerini 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:

    • Apple Geliştirici hesabınız için bir Apple Anında Bildirim Kimlik Doğrulama Anahtarı edinin.
    • Uygulama > Yetenekler altında XCode'da Anında Bildirimleri etkinleştirin.

Henüz bir Xcode projeniz yoksa ve yalnızca bir Firebase ürününü denemek istiyorsanız hızlı başlangıç ​​örneklerimizden birini indirebilirsiniz.

Firebase projesi oluşturma

Firebase'i Apple uygulamanıza ekleyebilmeniz için önce uygulamanıza bağlanacak bir Firebase projesi oluşturmanız gerekir. Firebase projeleri hakkında daha fazla bilgi edinmek için Firebase Projelerini Anlayın sayfasını ziyaret edin.

Uygulamanızı Firebase'e kaydedin

Firebase'i Apple uygulamanızda kullanmak için uygulamanızı Firebase projenize kaydetmeniz gerekir. Uygulamanızı kaydetmeye genellikle uygulamanızı projenize "eklemek" denir.

  1. Firebase konsoluna gidin.

  2. Kurulum iş akışını başlatmak için projeye genel bakış sayfasının ortasındaki iOS+ simgesine tıklayın.

    Firebase projenize zaten bir uygulama eklediyseniz platform seçeneklerini görüntülemek için Uygulama ekle'yi tıklayın.

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

  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ı ekleyin

  1. Firebase Apple platformları yapılandırma dosyanızı ( GoogleService-Info.plist ) edinmek için GoogleService-Info.plist'i İndir'i tıklayın.

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

Projenizde birden fazla paket kimliğiniz varsa her uygulamanın kendi GoogleService-Info.plist dosyasına sahip olabilmesi için her paket kimliğini Firebase konsolundaki kayıtlı bir uygulamayla ilişkilendirmeniz gerekir.

Firebase SDK'larını uygulamanıza ekleyin

Firebase bağımlılıklarını yüklemek ve yönetmek için Swift Paket Yöneticisini kullanın.

  1. Xcode'da uygulama projeniz açıkken Dosya > Paket Ekle'ye gidin.
  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 bayrağını hedefinizin derleme ayarlarının Diğer Bağlayıcı Bayrakları bölümüne ekleyin.
  6. Firebase Cloud Messaging ile en iyi deneyimi elde etmek için Firebase projenizde Google Analytics'i etkinleştirmenizi ve Google Analytics için Firebase SDK'sını uygulamanıza eklemenizi öneririz. IDFA koleksiyonu olmayan veya IDFA koleksiyonu olan kütüphaneyi seçebilirsiniz.
  7. Bitirdiğinizde Xcode, bağımlılıklarınızı arka planda otomatik olarak çözmeye ve indirmeye başlayacaktır.

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

APN kimlik doğrulama anahtarınızı Firebase'e yükleyin. Henüz bir APN kimlik doğrulama anahtarınız yoksa Apple Geliştirici Üye Merkezi'nde bir tane oluşturduğunuzdan emin olun.

  1. Firebase konsolundaki projenizin içinde dişli simgesini seçin, Proje Ayarları'nı ve ardından Bulut Mesajlaşma sekmesini seçin.

  2. iOS uygulama yapılandırması altındaki APN kimlik doğrulama anahtarında Yükle düğmesini tıklayın.

  3. Anahtarınızı kaydettiğiniz konuma göz atın, onu seçin ve Aç'ı tıklayın. Anahtarın anahtar kimliğini ekleyin ( Apple Geliştirici Üye Merkezi'nde mevcuttur) ve Yükle'yi tıklayın.

Uygulamanızda Firebase'i başlatın

Uygulamanıza Firebase başlatma kodunu eklemeniz gerekecek. Firebase modülünü içe aktarın ve paylaşılan bir örneği gösterildiği gibi yapılandırın:

  1. FirebaseCore modülünü UIApplicationDelegate ve uygulama temsilcinizin kullandığı diğer Firebase modüllerine aktarın. Örneğin, Cloud Firestore ve Authentication'ı kullanmak için:

    SwiftUI

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

    Süratli

    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Amaç-C

    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  2. Uygulama temsilcinizin application(_:didFinishLaunchingWithOptions:) yönteminde FirebaseApp paylaşılan örneğini yapılandırın:

    SwiftUI

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

    Süratli

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

    Amaç-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  3. SwiftUI kullanıyorsanız, bir uygulama temsilcisi oluşturmalı ve bunu UIApplicationDelegateAdaptor veya NSApplicationDelegateAdaptor aracılığıyla App yapınıza eklemelisiniz. Ayrıca uygulama temsilcisinin swizzling özelliğini de devre dışı bırakmalısınız. Daha fazla bilgi için SwiftUI talimatlarına bakın.

    SwiftUI

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

Uzaktan bildirimler için kaydolun

Başlangıçta veya uygulama akışınızın istediğiniz noktasında uygulamanızı uzaktan bildirimler için kaydedin. registerForRemoteNotifications gösterildiği gibi çağırın:

Süratli


UNUserNotificationCenter.current().delegate = self

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

application.registerForRemoteNotifications()

Amaç-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ı bir konuya abone olma

İstemci uygulamaları mevcut herhangi bir konuya abone olabilir veya yeni bir konu oluşturabilir. Bir istemci uygulaması yeni bir konu adına abone olduğunda (Firebase projeniz için halihazırda mevcut olmayan bir konu), FCM'de bu adda yeni bir konu oluşturulur ve herhangi bir istemci daha sonra bu konuya abone olabilir.

Bir konuya abone olmak için uygulamanızın ana iş parçacığından 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, aşağıdaki şekilde gösterildiği gibi tamamlama işleyicisinde yakalayabileceğiniz bir hata atar:

Süratli

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

Amaç-C

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

Bu çağrı, FCM arka ucuna eşzamansız bir istekte bulunur ve istemcinin verilen konuya abone olmasını sağlar. subscribeToTopic:topic çağırmadan önce, istemci uygulaması örneğinin didReceiveRegistrationToken geri çağrısı aracılığıyla zaten bir kayıt belirteci aldığından emin olun.

Uygulama her başlatıldığında FCM, istenen tüm konuların abone olduğundan emin olur. Abonelikten çıkmak için unsubscribeFromTopic:topic çağrısını yapın ve FCM arka planda konunun aboneliğini iptal eder.

Konu mesajlarını alma ve yönetme

FCM, konu mesajlarını diğer alt mesajlarla aynı şekilde iletir.

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

Süratli

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
}

Amaç-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

İstemci uygulaması örneklerini istemci tarafındaki konuya abone olarak veya sunucu API'si aracılığıyla bir konu oluşturduktan sonra konuya ileti gönderebilirsiniz. FCM için ilk kez gönderme istekleri oluşturuyorsanız, önemli arka plan ve kurulum bilgileri için sunucu ortamınıza ve FCM kılavuzuna bakın.

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

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)

Gitmek

// 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);

DİNLENMEK

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

Konuların bir kombinasyonuna mesaj göndermek için, hedef konuları belirten bir boole ifadesi olan bir koşul belirtin. Örneğin, aşağıdaki koşul TopicA ve TopicB veya TopicC abone olan cihazlara mesaj gönderecektir:

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

FCM önce parantez içindeki koşulları değerlendirir, ardından ifadeyi soldan sağa doğru değerlendirir. Yukarıdaki ifadede herhangi bir konuya abone olan kullanıcı mesajı almıyor. Aynı şekilde TopicA abone olmayan bir kullanıcı da mesajı alamamaktadır. Bu kombinasyonlar bunu alır:

  • 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)

Gitmek

// 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);

DİNLENMEK

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