了解 2023 年 Google I/O 大会上介绍的 Firebase 亮点。了解详情

Apple platformlarında birden fazla cihaza mesaj gönderin

Firebase Cloud Messaging, bir mesajı birden fazla cihaza hedeflemek için iki yol sunar:

  • Belirli bir konuyu seçmiş olan birden fazla cihaza mesaj göndermenizi sağlayan konu mesajlaşması .
  • Bir gruba ait cihazlarda çalışan bir uygulamanın birden fazla örneğine tek bir mesaj göndermenizi sağlayan cihaz grubu mesajlaşması .

Bu eğitim, Admin SDK veya FCM için REST API kullanarak uygulama sunucunuzdan konu mesajları göndermeye ve bunları bir Apple uygulamasında alıp işlemeye odaklanır. Bu sayfada, kurulumdan doğrulamaya kadar bunu başarmak için atılacak tüm adımlar listelenmektedir; bu nedenle, FCM için bir Apple istemci uygulaması kurduysanız veya İlk Mesajınızı Gönderme adımlarını uyguladıysanız zaten 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, APNs kimlik doğrulama anahtarınızı yüklemeniz ve uzaktan bildirimler için kaydolmanız gerekir.

Önkoşullar

  • Aşağıdakileri yükleyin:

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

    • Projeniz şu platform sürümlerini veya sonraki sürümleri hedeflemelidir:
      • iOS 11
      • macOS 10.13
      • tvOS 12
      • OS 6 izle
  • Uygulamanızı çalıştırmak için fiziksel bir Apple aygıtı 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.
    • App > Capabilities altında XCode'da Push Bildirimlerini etkinleştirin.

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

Bir Firebase projesi oluşturun

Firebase'i Apple uygulamanıza ekleyebilmeniz için uygulamanıza bağlanmak üzere 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ı kaydettirmek genellikle uygulamanızı projenize "eklemek" olarak adlandırılır.

  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 Uygulama Mağazası Kimliği .

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

Bir 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üne taşıyın. İstenirse, yapılandırma dosyasını tüm hedeflere eklemek için 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 konsolunda kayıtlı bir uygulamayla ilişkilendirmeniz gerekir.

Uygulamanıza Firebase SDK'ları ekleyin

Firebase bağımlılıklarını kurmak ve yönetmek için Swift Paket Yöneticisi'ni kullanın.

  1. Xcode'da, uygulama projeniz açıkken File > Add Packages seçeneğine gidin.
  2. İstendiğinde, Firebase Apple platformları SDK deposunu ekleyin:
  3.   https://github.com/firebase/firebase-ios-sdk
  4. Firebase Cloud Messaging kitaplığını seçin.
  5. Firebase Cloud Messaging ile optimum bir deneyim için Firebase projenizde Google Analytics'i etkinleştirmenizi ve Google Analytics için Firebase SDK'yı uygulamanıza eklemenizi öneririz. Kütüphaneyi IDFA koleksiyonu olmadan veya IDFA koleksiyonu ile seçebilirsiniz.
  6. Bittiğinde, Xcode otomatik olarak arka planda bağımlılıklarınızı çözmeye ve indirmeye başlayacaktır.

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

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

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

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

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

Uygulamanızda Firebase'i başlatın

Uygulamanıza Firebase başlatma kodu 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. UIApplicationDelegate uygulamanıza FirebaseCore modülünü ve uygulama temsilcinizin kullandığı diğer Firebase modüllerini içe 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 bir FirebaseApp paylaşılan örneği 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. Uygulama temsilcisi swizzling'i 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ızda istenen noktada, uygulamanızı uzaktan bildirimler için kaydedin. registerForRemoteNotifications gösterildiği gibi arayı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 olun

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

Bir konuya abone olmak için, uygulamanızın ana ileti dizisinden 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, gösterildiği gibi bir 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 istemciyi verilen konuya abone olur. subscribeToTopic:topic çağırmadan önce, istemci uygulaması örneğinin, didReceiveRegistrationToken geri araması aracılığıyla zaten bir kayıt belirteci aldığından emin olun.

Uygulama her başladığında, FCM istenen tüm konuların abone olduğundan emin olur. Abonelikten çıkmak için, unsubscribeFromTopic:topic arayın ve FCM, arka planda konuyla ilgili abonelikten çıkar.

Konu mesajlarını alın ve işleyin

FCM, konu mesajlarını diğer aşağı akış mesajlarıyla 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şturun

İstemci uygulama örneklerini konuya istemci tarafında abone olarak veya sunucu API'si aracılığıyla bir konu oluşturduktan sonra konuya mesaj 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'ye ilişkin kılavuza 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);

Piton

# 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

Bir konu kombinasyonuna mesaj göndermek için, hedef konuları belirten bir mantıksal ifade olan bir koşul belirtin. Örneğin, aşağıdaki koşul, TopicA ve TopicB veya TopicC abone olan cihazlara mesaj gönderir:

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

FCM önce herhangi bir koşulu parantez içinde değerlendirir ve ardından ifadeyi soldan sağa doğru değerlendirir. Yukarıdaki ifadede herhangi bir konuya üye olan kullanıcı mesajı almamaktadır. Aynı şekilde TopicA abone olmayan bir kullanıcı mesajı almaz. 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);

Piton

# 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