در پلتفرم های اپل به چندین دستگاه پیام بفرستید

برای هدف قرار دادن یک پیام به چندین دستگاه، از پیام‌رسانی موضوع استفاده کنید. این ویژگی به شما امکان می دهد پیامی را به چندین دستگاهی که موضوع خاصی را انتخاب کرده اند ارسال کنید.

این آموزش بر ارسال پیام‌های موضوعی از سرور برنامه شما با استفاده از Admin SDK یا REST API برای FCM، و دریافت و مدیریت آنها در یک برنامه Apple تمرکز دارد. این صفحه تمام مراحل برای رسیدن به این هدف را از راه‌اندازی تا تأیید فهرست می‌کند - بنابراین اگر یک برنامه مشتری Apple برای FCM راه‌اندازی کرده باشید یا مراحل ارسال اولین پیام خود را انجام داده باشید، ممکن است مراحلی را که قبلاً انجام داده‌اید را پوشش دهد.

Firebase را به پروژه اپل خود اضافه کنید

اگر قبلاً سایر ویژگی های Firebase را برای برنامه خود فعال کرده باشید، این بخش وظایفی را که ممکن است انجام داده باشید را پوشش می دهد. مخصوصاً برای FCM، باید کلید احراز هویت APN خود را آپلود کنید و برای اعلان های راه دور ثبت نام کنید .

پیش نیازها

  • موارد زیر را نصب کنید:

    • Xcode 14.1 یا بالاتر
  • اطمینان حاصل کنید که پروژه شما این شرایط را برآورده می کند:

    • پروژه شما باید این نسخه های پلتفرم یا جدیدتر را هدف قرار دهد:
      • iOS 11
      • macOS 10.13
      • tvOS 12
      • watchOS 6
  • یک دستگاه اپل فیزیکی را برای اجرای برنامه خود تنظیم کنید و این کارها را کامل کنید:

    • یک کلید تأیید اعتبار Apple Push Notification برای حساب Apple Developer خود دریافت کنید.
    • Push Notifications را در XCode در قسمت App > Capabilities فعال کنید.

اگر قبلاً پروژه Xcode ندارید و فقط می‌خواهید یک محصول Firebase را امتحان کنید، می‌توانید یکی از نمونه‌های شروع سریع ما را دانلود کنید.

یک پروژه Firebase ایجاد کنید

قبل از اینکه بتوانید Firebase را به برنامه Apple خود اضافه کنید، باید یک پروژه Firebase برای اتصال به برنامه خود ایجاد کنید. برای کسب اطلاعات بیشتر در مورد پروژه های Firebase ، از Understand Firebase Projects دیدن کنید.

برنامه خود را با Firebase ثبت کنید

برای استفاده از Firebase در برنامه Apple خود، باید برنامه خود را در پروژه Firebase خود ثبت کنید. ثبت برنامه شما اغلب "افزودن" برنامه شما به پروژه شما نامیده می شود.

  1. به کنسول Firebase بروید.

  2. در مرکز صفحه نمای کلی پروژه، روی نماد iOS+ کلیک کنید تا گردش کار راه اندازی شود.

    اگر قبلاً برنامه‌ای را به پروژه Firebase خود اضافه کرده‌اید، روی افزودن برنامه کلیک کنید تا گزینه‌های پلتفرم نمایش داده شوند.

  3. شناسه بسته نرم افزاری خود را در قسمت شناسه بسته وارد کنید.

  4. (اختیاری) اطلاعات دیگر برنامه را وارد کنید: نام مستعار برنامه و شناسه فروشگاه App .

  5. روی ثبت برنامه کلیک کنید.

یک فایل پیکربندی Firebase اضافه کنید

  1. برای دریافت فایل پیکربندی پلتفرم های اپل Firebase ( GoogleService-Info.plist ) روی Download GoogleService-Info.plist کلیک کنید.

  2. فایل پیکربندی خود را به ریشه پروژه Xcode خود منتقل کنید. اگر از شما خواسته شد، انتخاب کنید تا فایل پیکربندی را به همه اهداف اضافه کنید.

اگر چندین شناسه بسته در پروژه خود دارید، باید هر ID بسته را با یک برنامه ثبت شده در کنسول Firebase مرتبط کنید تا هر برنامه بتواند فایل GoogleService-Info.plist خود را داشته باشد.

SDK های Firebase را به برنامه خود اضافه کنید

برای نصب و مدیریت وابستگی های Firebase از Swift Package Manager استفاده کنید.

  1. در Xcode، با باز بودن پروژه برنامه، به File > Add Packages بروید.
  2. هنگامی که از شما خواسته شد، مخزن SDK پلتفرم های Apple Firebase را اضافه کنید:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. کتابخانه Firebase Cloud Messaging را انتخاب کنید.
  5. پرچم -ObjC را به بخش Other Linker Flags تنظیمات ساخت هدف خود اضافه کنید.
  6. برای تجربه بهینه با Firebase Cloud Messaging، توصیه می‌کنیم Google Analytics را در پروژه Firebase خود فعال کنید و Firebase SDK برای Google Analytics را به برنامه خود اضافه کنید. شما می توانید کتابخانه را بدون مجموعه IDFA یا با مجموعه IDFA انتخاب کنید.
  7. پس از اتمام، Xcode به طور خودکار شروع به حل و دانلود وابستگی های شما در پس زمینه می کند.

کلید احراز هویت APN خود را آپلود کنید

کلید احراز هویت APN خود را در Firebase آپلود کنید. اگر از قبل یک کلید تأیید اعتبار APN ندارید، مطمئن شوید که در مرکز اعضای برنامه‌نویس Apple ایجاد کرده‌اید.

  1. در داخل پروژه خود در کنسول Firebase، نماد چرخ دنده را انتخاب کنید، تنظیمات پروژه را انتخاب کنید و سپس برگه Cloud Messaging را انتخاب کنید.

  2. در کلید احراز هویت APN در پیکربندی برنامه iOS ، روی دکمه آپلود کلیک کنید.

  3. به مکانی که کلید خود را در آن ذخیره کرده اید بروید، آن را انتخاب کنید و روی Open کلیک کنید. شناسه کلید را برای کلید اضافه کنید (در مرکز اعضای برنامه نویس اپل موجود است) و روی آپلود کلیک کنید.

Firebase را در برنامه خود راه اندازی کنید

شما باید کد اولیه Firebase را به برنامه خود اضافه کنید. ماژول Firebase را وارد کنید و یک نمونه مشترک را مطابق شکل پیکربندی کنید:

  1. ماژول FirebaseCore را در UIApplicationDelegate خود و همچنین هر ماژول Firebase دیگری که نماینده برنامه شما استفاده می‌کند، وارد کنید. به عنوان مثال، برای استفاده از Cloud Firestore و Authentication:

    SwiftUI

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

    سریع

    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    هدف-C

    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  2. یک نمونه اشتراک‌گذاری شده FirebaseApp در روش برنامه نماینده برنامه خود application(_:didFinishLaunchingWithOptions:) پیکربندی کنید:

    SwiftUI

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

    سریع

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

    هدف-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  3. اگر از SwiftUI استفاده می‌کنید، باید یک نماینده برنامه ایجاد کنید و آن را از طریق UIApplicationDelegateAdaptor یا NSApplicationDelegateAdaptor به ساختار App خود متصل کنید. همچنین باید swizzling نمایندگی برنامه را غیرفعال کنید. برای اطلاعات بیشتر، دستورالعمل های SwiftUI را ببینید.

    SwiftUI

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

برای اطلاعیه از راه دور ثبت نام کنید

در هنگام راه اندازی یا در نقطه مورد نظر در جریان برنامه خود، برنامه خود را برای اعلان های راه دور ثبت کنید. مطابق شکل با registerForRemoteNotifications تماس بگیرید:

سریع


UNUserNotificationCenter.current().delegate = self

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

application.registerForRemoteNotifications()

هدف-C


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

[application registerForRemoteNotifications];

اشتراک برنامه مشتری در یک موضوع

برنامه های مشتری می توانند در هر موضوع موجود مشترک شوند یا می توانند موضوع جدیدی ایجاد کنند. هنگامی که یک برنامه مشتری در یک نام موضوع جدید مشترک می شود (نامی که قبلاً برای پروژه Firebase شما وجود ندارد)، موضوع جدیدی با آن نام در FCM ایجاد می شود و هر مشتری می تواند متعاقباً در آن مشترک شود.

برای اشتراک در یک موضوع، روش اشتراک را از رشته اصلی برنامه خود تماس بگیرید (FCM امن نیست). اگر درخواست اشتراک در ابتدا با شکست مواجه شد، FCM به طور خودکار دوباره تلاش می کند. برای مواردی که اشتراک نمی‌تواند تکمیل شود، اشتراک خطایی ایجاد می‌کند که می‌توانید در یک کنترل‌کننده تکمیل، همانطور که نشان داده شده است، آن را دریافت کنید:

سریع

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

هدف-C

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

این تماس یک درخواست ناهمزمان به باطن FCM می دهد و مشتری را در موضوع داده شده مشترک می کند. قبل از فراخوانی subscribeToTopic:topic ، مطمئن شوید که نمونه برنامه مشتری قبلاً یک نشانه ثبت نام از طریق callback didReceiveRegistrationToken دریافت کرده است.

هر بار که برنامه شروع می شود، FCM مطمئن می شود که همه موضوعات درخواستی مشترک شده اند. برای لغو اشتراک، با unsubscribeFromTopic:topic تماس بگیرید و FCM اشتراک موضوع را در پس‌زمینه لغو می‌کند.

دریافت و مدیریت پیام های موضوعی

FCM پیام های موضوعی را به همان روشی که سایر پیام های پایین دستی ارائه می دهد.

application(_:didReceiveRemoteNotification:fetchCompletionHandler:) را مطابق شکل پیاده کنید:

سریع

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
}

هدف-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);
}

ساخت درخواست های ارسال

پس از ایجاد یک موضوع، یا با اشتراک نمونه های برنامه مشتری در موضوع سمت مشتری یا از طریق API سرور ، می توانید پیام هایی را به موضوع ارسال کنید. اگر این اولین باری است که درخواست ارسال درخواست برای FCM را ایجاد می‌کنید، راهنمای محیط سرور و FCM را برای اطلاعات مربوط به پس‌زمینه و تنظیمات مهم ببینید.

در منطق ارسال خود در باطن، نام موضوع مورد نظر را مطابق شکل مشخص کنید:

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

جاوا

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

پایتون

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

برو

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

سی شارپ

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

باقی مانده

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:

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

برای ارسال پیام به ترکیبی از موضوعات، یک شرط را مشخص کنید، که یک عبارت بولی است که موضوعات مورد نظر را مشخص می کند. برای مثال، شرایط زیر پیام‌هایی را به دستگاه‌هایی ارسال می‌کند که مشترک TopicA و TopicB یا TopicC هستند:

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

FCM ابتدا هر شرایط داخل پرانتز را ارزیابی می کند و سپس عبارت را از چپ به راست ارزیابی می کند. در عبارت بالا، کاربری که در یک موضوع مشترک است، پیامی را دریافت نمی کند. به همین ترتیب، کاربری که در TopicA مشترک نمی شود، پیام را دریافت نمی کند. این ترکیبات آن را دریافت می کنند:

  • TopicA و TopicB
  • TopicA و TopicC

می توانید حداکثر پنج موضوع را در عبارت شرطی خود بگنجانید.

برای ارسال به یک شرط:

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

جاوا

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

پایتون

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

برو

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

سی شارپ

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

باقی مانده

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:

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

مراحل بعدی

  • می‌توانید از سرور خود برای اشتراک نمونه‌های برنامه مشتری در موضوعات و انجام سایر وظایف مدیریتی استفاده کنید. به مدیریت اشتراک موضوع در سرور مراجعه کنید.