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

Bir mesajı birden çok cihaza hedeflemek için Konu mesajlaşma'yı kullanın. Bu özellik, belirli bir konuya kaydolan birden fazla cihaza mesaj göndermenize olanak tanır.

Bu eğitim, FCM için Yönetici SDK'sı veya REST API'yi 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 bu işlemi gerçekleştirmek için izlemeniz gereken tüm adımlar listelenmiştir. Bu nedenle, FCM için bir Apple istemci uygulaması kurduysanız veya İlk Mesajınızı Gönderme adımlarını uyguladıysanız bu sayfada tamamladığınız adımlar ele alınabilir.

Firebase'i Apple projenize ekleyin

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

Ö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 aşağıdaki görevleri tamamlayın:

    • Apple Geliştirici hesabınız için bir Apple Anında Bildirim Kimlik Doğrulama Anahtarı edinin.
    • XCode'da Uygulama > Özellikler bölümünde Push Bildirimleri'ni etkinleştirin.

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 eklemeden önce uygulamanıza bağlanacak bir Firebase projesi oluşturmanız gerekir. Firebase projeleri hakkında daha fazla bilgi için Firebase Projelerini Anlama 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ı kaydetme işlemine genellikle uygulamanızı projenize "ekleme" denir.

  1. Firebase konsoluna gidin.

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

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

  3. Uygulamanızın paket kimliğini paket kimliği alanına 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ı ekleme

  1. Firebase Apple platforms yapılandırma dosyanızı (GoogleService-Info.plist) edinmek için GoogleService-Info.plist dosyasını indir'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 eklemeyi seçin.

Projenizde birden fazla paket kimliği 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.

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, uygulamanız açıkken File > Add Packages'a (Dosya > Paket Ekle) 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 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 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 toplama olmayan veya IDFA toplama içeren kitaplığı seçebilirsiniz.
  7. İşlem tamamlandığında Xcode, arka planda bağımlılıklarınızı otomatik olarak çözümlemeye ve indirmeye baş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 Developer Member Center'da bir tane oluşturduğunuzdan emin olun.

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

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

  3. Anahtarınızı kaydettiğiniz konuma gidin, anahtarı seçin ve 'ı 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

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

  1. FirebaseCore modülünü UIApplicationDelegate uygulamanıza ve yetki verdiğiniz kullanıcının kullandığı diğer tüm Firebase modüllerini içe aktarın. Ö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. Uygulama yetkilinizin application(_:didFinishLaunchingWithOptions:) yönteminde FirebaseApp paylaşılan bir örnek yapılandırın:

    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şturmanız ve UIApplicationDelegateAdaptor veya NSApplicationDelegateAdaptor aracılığıyla App yapınıza eklemeniz gerekir. Uygulama yetkilendirmesi kaydırmayı da devre dışı bırakmanız gerekir. 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 istediğiniz noktada uygulamanızı uzaktan bildirimler için kaydedin. Gösterildiği gibi registerForRemoteNotifications çağrısı yapın:

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. Bir istemci uygulaması yeni bir konu adına (Firebase projenizde zaten bulunmayan) abone olduğunda FCM'de bu ada sahip yeni bir konu oluşturulur ve herhangi bir müşteri 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ğıda gösterildiği gibi bir tamamlama işleyicide yakalayabileceğiniz bir hata verir:

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 bir istek gönderir ve istemciyi belirtilen konuya abone yapar. subscribeToTopic:topic işlevini çağırmadan önce, istemci uygulama örneğinin didReceiveRegistrationToken geri çağırması aracılığıyla zaten bir kayıt jetonu aldığından emin olun.

Uygulama her başlatıldığında FCM, istenen tüm konulara abone olunmasını sağlar. Abonelikten çıkmak için unsubscribeFromTopic:topic numaralı telefonu ararsanız FCM, arka planda bu konunun aboneliğinden çıkar.

Konu mesajlarını alma ve işleme

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

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

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 istemci tarafında konuya abone olarak veya sunucu API'si aracılığıyla konuya mesaj gönderebilirsiniz. FCM için gönderme isteklerini ilk kez oluşturuyorsanız önemli arka plan ve kurulum bilgileri için sunucu ortamınız 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)

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

Bir konu kombinasyonuna mesaj göndermek için bir koşul belirtin. Bu koşul, hedef konuları belirten bir boole ifadesidir. Örneğin, aşağıdaki koşul TopicA ve TopicB ya da TopicC aboneliklerine abone olan cihazlara mesaj gönderir:

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

FCM, önce parantez içindeki tüm koşulları ve daha sonra, soldan sağa doğru ifadeyi değerlendirir. Yukarıdaki ifadede, herhangi bir konuya abone olan kullanıcı mesajı almaz. Benzer şekilde, TopicA hizmetine abone olmayan kullanıcı da bu iletiyi almaz. Şu 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)

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

  • İstemci uygulaması örneklerini konulara abone olmak ve diğer yönetim görevlerini gerçekleştirmek için sunucunuzu kullanabilirsiniz. Sunucudaki konu aboneliklerini yönetme bölümünü inceleyin.