Firebase Cloud Messaging, bir mesajı birden çok cihaza hedeflemenin iki yolunu sunar:
- Belirli bir konuyu seçmiş birden fazla cihaza mesaj göndermenize olanak sağlayan konu mesajlaşma .
- Bir gruba ait cihazlarda çalışan bir uygulamanın birden çok örneğine tek bir mesaj göndermenizi sağlayan cihaz grubu mesajlaşma .
Bu eğitici, FCM için Admin SDK veya REST API kullanarak uygulama sunucunuzdan konu mesajları göndermeye ve bunları bir Apple uygulamasında alıp işlemeye odaklanır. Bu sayfa, kurulumdan doğrulamaya kadar bunu başarmak için tüm adımları listeler - bu nedenle, FCM için bir Apple istemci uygulaması kurduysanız veya İlk Mesajınızı Gönderme adımlarını tamamladıysanız, zaten tamamladığınız adımları kapsayabilir.
Apple projenize Firebase 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 13.3.1 veya üstü
Projenizin şu gereksinimleri karşıladığından emin olun:
- Projeniz bu platform sürümlerini veya daha sonrasını hedeflemelidir:
- iOS 10
- macOS 10.12
- tvOS 12
- watchOS 6
- Projeniz bu platform sürümlerini veya daha sonrasını hedeflemelidir:
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.
- XCode'da App > Capabilities altında Push Bildirimlerini etkinleştirin.
- Google hesabınızı kullanarak Firebase'de oturum açın.
Halihazırda bir Xcode projeniz yoksa ve yalnızca bir Firebase ürününü denemek istiyorsanız, hızlı başlangıç örneklerimizden birini indirebilirsiniz.
Bir Firebase projesi oluşturun
Firebase'i Apple uygulamanıza eklemeden önce uygulamanıza bağlanmak için 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.
Firebase konsoluna gidin.
Projeye genel bakış sayfasının ortasında, kurulum iş akışını başlatmak için 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.
Paket kimliği alanına uygulamanızın paket kimliğini girin.
Paket kimliği , Apple ekosistemindeki bir uygulamayı benzersiz şekilde tanımlar.
Paket kimliğinizi bulun: projenizi Xcode'da açın, proje gezgininde en üst düzey uygulamayı seçin, ardından Genel sekmesini seçin.
Paket Tanımlayıcı alanının değeri, paket kimliğidir (örneğin,
com.yourcompany.yourproject
).Paket kimliği değerinin büyük/küçük harf duyarlı olduğunu ve Firebase projenize kaydolduktan sonra bu Firebase uygulaması için değiştirilemeyeceğini unutmayın.
(İsteğe bağlı) Diğer uygulama bilgilerini girin: Uygulama takma adı ve Uygulama Mağazası Kimliği .
Uygulama takma adı : Yalnızca Firebase konsolunda görebileceğiniz dahili, kullanışlı bir tanımlayıcı
App Store Kimliği : Kullanıcıları App Store sayfanıza yönlendirmek için Firebase Dynamic Links ve dönüşüm etkinliklerini Google Ads'e aktarmak için Google Analytics tarafından kullanılır. Uygulamanızın henüz bir App Store Kimliği yoksa, kimliği daha sonra Proje ayarlarınızdan ekleyebilirsiniz.
Uygulamayı kaydet'i tıklayın.
Firebase yapılandırma dosyası ekleyin
Firebase Apple platformları yapılandırma dosyanızı (
GoogleService-Info.plist
) almak için GoogleService-Info.plist'i İndir'i tıklayın.Firebase yapılandırma dosyası, projeniz için benzersiz, ancak gizli olmayan tanımlayıcılar içerir. Bu yapılandırma dosyası hakkında daha fazla bilgi edinmek için Firebase Projelerini Anlayın sayfasını ziyaret edin.
Firebase yapılandırma dosyanızı istediğiniz zaman yeniden indirebilirsiniz.
Yapılandırma dosyası adının sonuna
(2)
gibi ek karakterler eklenmediğinden emin olun.
Yapılandırma dosyanızı Xcode projenizin kök dizinine 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.
- Xcode'da, uygulama projeniz açıkken File > Add Packages seçeneğine gidin.
- İstendiğinde, Firebase Apple platformları SDK deposunu ekleyin:
- Firebase Bulut Mesajlaşma kitaplığını seçin.
- Firebase Cloud Messaging ile optimum deneyim 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.
- Bittiğinde, Xcode otomatik olarak bağımlılıklarınızı arka planda çözmeye ve indirmeye başlayacaktır.
https://github.com/firebase/firebase-ios-sdk
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 Üye Merkezi'nde bir tane oluşturduğunuzdan emin olun.
Firebase konsolunda projenizin içinde dişli simgesini seçin, Project Settings öğesini seçin ve ardından Cloud Messaging sekmesini seçin.
iOS uygulama yapılandırması altındaki APNs kimlik doğrulama anahtarında , Yükle düğmesini tıklayın.
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 bulunur ) 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:
-
UIApplicationDelegate
FirebaseCore
modülünü ve uygulama temsilcinizin kullandığı diğer Firebase modüllerini içe aktarın. Örneğin, Cloud Firestore ve Kimlik Doğrulamayı kullanmak için:Süratli
import FirebaseCore import FirebaseFirestore import FirebaseAuth // ...
Amaç-C
@import FirebaseCore; @import FirebaseFirestore; @import FirebaseAuth; // ...
- Genellikle
App
başlatıcısında veya uygulama temsilcisininapplication(_:didFinishLaunchingWithOptions:)
yönteminde birFirebaseApp
paylaşılan örneği yapılandırın:Süratli
// Use Firebase library to configure APIs FirebaseApp.configure()
Amaç-C
// Use Firebase library to configure APIs [FIRApp configure];
Uzaktan bildirimler için kaydolun
İster başlangıçta ister uygulama akışınızın istediğiniz noktasında, uygulamanızı uzaktan bildirimler için kaydedin.registerForRemoteNotifications
için gösterildiği gibi arayın:Süratli
if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: { _, _ in } ) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications()
Amaç-C
if ([UNUserNotificationCenter class] != nil) { // iOS 10 or later // For iOS 10 display notification (sent via APNS) [UNUserNotificationCenter currentNotificationCenter].delegate = self; UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge; [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { // ... }]; } else { // iOS 10 notifications aren't available; fall back to iOS 8-9 notifications. UIUserNotificationType allNotificationTypes = (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge); UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil]; [application registerUserNotificationSettings:settings]; } [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 isimde yeni bir konu oluşturulur ve ardından herhangi bir müşteri buna 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ığı için 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 gibi bir tamamlama işleyicisinde yakalayabileceğiniz bir hata verir:
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 yapar. subscribeToTopic:topic
öğesini çağırmadan önce, istemci uygulama ö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. Aboneliği iptal etmek için unsubscribeFromTopic:topic
öğesini arayın ve FCM arka planda konunun aboneliğini iptal eder.
Konu mesajlarını alın ve işleyin
FCM, konu mesajlarını diğer aşağı akış mesajlarıyla aynı şekilde sunar.
application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
gösterildiği gibi uygulayın:
Süratli
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // 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) completionHandler(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ştur
Bir konu oluşturduktan sonra, ya istemci tarafında konuya istemci uygulama örnekleri aboneliği yaparak ya da sunucu API'si aracılığıyla 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ız ve FCM kılavuzuna bakın.
Arka uçtaki gönderme mantığınızda, gösterildiği gibi istediğiniz konu adını 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İNLENME
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 boole ifadesi 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 parantez içindeki koşulları değerlendirir ve ardından ifadeyi soldan sağa doğru değerlendirir. Yukarıdaki ifadede herhangi bir konuya abone olan bir kullanıcı mesajı almaz. Aynı şekilde TopicA
abone olmayan bir kullanıcı da mesajı almaz. Bu kombinasyonlar bunu alır:
-
TopicA
veTopicB
-
TopicA
veTopicC
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İNLENME
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 uygulama örneklerine konulara abone olmak ve diğer yönetim görevlerini gerçekleştirmek için sunucunuzu kullanabilirsiniz. Sunucudaki konu aboneliklerini yönetme konusuna bakın.
- Birden fazla cihaza göndermenin diğer yolu hakkında daha fazla bilgi edinin — Cihaz grubu mesajlaşma