2 * Copyright 2017 Google
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #import <Foundation/Foundation.h>
19 NS_ASSUME_NONNULL_BEGIN
22 * @related FIRMessaging
24 * The completion handler invoked when the registration token returns.
25 * If the call fails we return the appropriate `error code`, described by
26 * `FIRMessagingError`.
28 * @param FCMToken The valid registration token returned by FCM.
29 * @param error The error describing why a token request failed. The error code
30 * will match a value from the FIRMessagingError enumeration.
32 typedef void(^FIRMessagingFCMTokenFetchCompletion)(NSString * _Nullable FCMToken,
33 NSError * _Nullable error)
34 NS_SWIFT_NAME(MessagingFCMTokenFetchCompletion);
38 * @related FIRMessaging
40 * The completion handler invoked when the registration token deletion request is
41 * completed. If the call fails we return the appropriate `error code`, described
42 * by `FIRMessagingError`.
44 * @param error The error describing why a token deletion failed. The error code
45 * will match a value from the FIRMessagingError enumeration.
47 typedef void(^FIRMessagingDeleteFCMTokenCompletion)(NSError * _Nullable error)
48 NS_SWIFT_NAME(MessagingDeleteFCMTokenCompletion);
51 * Callback to invoke once the HTTP call to FIRMessaging backend for updating
52 * subscription finishes.
54 * @param error The error which occurred while updating the subscription topic
55 * on the FIRMessaging server. This will be nil in case the operation
56 * was successful, or if the operation was cancelled.
58 typedef void (^FIRMessagingTopicOperationCompletion)(NSError *_Nullable error);
61 * The completion handler invoked once the data connection with FIRMessaging is
62 * established. The data connection is used to send a continous stream of
63 * data and all the FIRMessaging data notifications arrive through this connection.
64 * Once the connection is established we invoke the callback with `nil` error.
65 * Correspondingly if we get an error while trying to establish a connection
66 * we invoke the handler with an appropriate error object and do an
67 * exponential backoff to try and connect again unless successful.
69 * @param error The error object if any describing why the data connection
70 * to FIRMessaging failed.
72 typedef void(^FIRMessagingConnectCompletion)(NSError * __nullable error)
73 NS_SWIFT_NAME(MessagingConnectCompletion)
74 __deprecated_msg("Please listen for the FIRMessagingConnectionStateChangedNotification "
75 "NSNotification instead.");
77 #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
79 * Notification sent when the upstream message has been delivered
80 * successfully to the server. The notification object will be the messageID
81 * of the successfully delivered message.
83 FOUNDATION_EXPORT const NSNotificationName FIRMessagingSendSuccessNotification
84 NS_SWIFT_NAME(MessagingSendSuccess);
87 * Notification sent when the upstream message was failed to be sent to the
88 * server. The notification object will be the messageID of the failed
89 * message. The userInfo dictionary will contain the relevant error
90 * information for the failure.
92 FOUNDATION_EXPORT const NSNotificationName FIRMessagingSendErrorNotification
93 NS_SWIFT_NAME(MessagingSendError);
96 * Notification sent when the Firebase messaging server deletes pending
97 * messages due to exceeded storage limits. This may occur, for example, when
98 * the device cannot be reached for an extended period of time.
100 * It is recommended to retrieve any missing messages directly from the
103 FOUNDATION_EXPORT const NSNotificationName FIRMessagingMessagesDeletedNotification
104 NS_SWIFT_NAME(MessagingMessagesDeleted);
107 * Notification sent when Firebase Messaging establishes or disconnects from
108 * an FCM socket connection. You can query the connection state in this
109 * notification by checking the `isDirectChannelEstablished` property of FIRMessaging.
111 FOUNDATION_EXPORT const NSNotificationName FIRMessagingConnectionStateChangedNotification
112 NS_SWIFT_NAME(MessagingConnectionStateChanged);
115 * Notification sent when the FCM registration token has been refreshed. Please use the
116 * FIRMessaging delegate method `messaging:didReceiveRegistrationToken:` to receive current and
119 FOUNDATION_EXPORT const NSNotificationName
120 FIRMessagingRegistrationTokenRefreshedNotification
121 NS_SWIFT_NAME(MessagingRegistrationTokenRefreshed);
124 * Notification sent when the upstream message has been delivered
125 * successfully to the server. The notification object will be the messageID
126 * of the successfully delivered message.
128 FOUNDATION_EXPORT NSString *const FIRMessagingSendSuccessNotification
129 NS_SWIFT_NAME(MessagingSendSuccessNotification);
132 * Notification sent when the upstream message was failed to be sent to the
133 * server. The notification object will be the messageID of the failed
134 * message. The userInfo dictionary will contain the relevant error
135 * information for the failure.
137 FOUNDATION_EXPORT NSString *const FIRMessagingSendErrorNotification
138 NS_SWIFT_NAME(MessagingSendErrorNotification);
141 * Notification sent when the Firebase messaging server deletes pending
142 * messages due to exceeded storage limits. This may occur, for example, when
143 * the device cannot be reached for an extended period of time.
145 * It is recommended to retrieve any missing messages directly from the
148 FOUNDATION_EXPORT NSString *const FIRMessagingMessagesDeletedNotification
149 NS_SWIFT_NAME(MessagingMessagesDeletedNotification);
152 * Notification sent when Firebase Messaging establishes or disconnects from
153 * an FCM socket connection. You can query the connection state in this
154 * notification by checking the `isDirectChannelEstablished` property of FIRMessaging.
156 FOUNDATION_EXPORT NSString *const FIRMessagingConnectionStateChangedNotification
157 NS_SWIFT_NAME(MessagingConnectionStateChangedNotification);
160 * Notification sent when the FCM registration token has been refreshed. Please use the
161 * FIRMessaging delegate method `messaging:didReceiveRegistrationToken:` to receive current and
164 FOUNDATION_EXPORT NSString *const FIRMessagingRegistrationTokenRefreshedNotification
165 NS_SWIFT_NAME(MessagingRegistrationTokenRefreshedNotification);
166 #endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
169 * @enum FIRMessagingError
171 typedef NS_ENUM(NSUInteger, FIRMessagingError) {
173 FIRMessagingErrorUnknown = 0,
175 /// FIRMessaging couldn't validate request from this client.
176 FIRMessagingErrorAuthentication = 1,
178 /// InstanceID service cannot be accessed.
179 FIRMessagingErrorNoAccess = 2,
181 /// Request to InstanceID backend timed out.
182 FIRMessagingErrorTimeout = 3,
184 /// No network available to reach the servers.
185 FIRMessagingErrorNetwork = 4,
187 /// Another similar operation in progress, bailing this one.
188 FIRMessagingErrorOperationInProgress = 5,
190 /// Some parameters of the request were invalid.
191 FIRMessagingErrorInvalidRequest = 7,
192 } NS_SWIFT_NAME(MessagingError);
194 /// Status for the downstream message received by the app.
195 typedef NS_ENUM(NSInteger, FIRMessagingMessageStatus) {
197 FIRMessagingMessageStatusUnknown,
198 /// New downstream message received by the app.
199 FIRMessagingMessageStatusNew,
200 } NS_SWIFT_NAME(MessagingMessageStatus);
203 * The APNS token type for the app. If the token type is set to `UNKNOWN`
204 * Firebase Messaging will implicitly try to figure out what the actual token type
205 * is from the provisioning profile.
206 * Unless you really need to specify the type, you should use the `APNSToken`
209 typedef NS_ENUM(NSInteger, FIRMessagingAPNSTokenType) {
210 /// Unknown token type.
211 FIRMessagingAPNSTokenTypeUnknown,
212 /// Sandbox token type.
213 FIRMessagingAPNSTokenTypeSandbox,
214 /// Production token type.
215 FIRMessagingAPNSTokenTypeProd,
216 } NS_SWIFT_NAME(MessagingAPNSTokenType);
218 /// Information about a downstream message received by the app.
219 NS_SWIFT_NAME(MessagingMessageInfo)
220 @interface FIRMessagingMessageInfo : NSObject
222 /// The status of the downstream message
223 @property(nonatomic, readonly, assign) FIRMessagingMessageStatus status;
228 * A remote data message received by the app via FCM (not just the APNs interface).
230 * This is only for devices running iOS 10 or above. To support devices running iOS 9 or below, use
231 * the local and remote notifications handlers defined in UIApplicationDelegate protocol.
233 NS_SWIFT_NAME(MessagingRemoteMessage)
234 @interface FIRMessagingRemoteMessage : NSObject
236 /// The downstream message received by the application.
237 @property(nonatomic, readonly, strong) NSDictionary *appData;
242 * A protocol to handle token update or data message delivery from FCM.
245 NS_SWIFT_NAME(MessagingDelegate)
246 @protocol FIRMessagingDelegate <NSObject>
249 /// This method will be called once a token is available, or has been refreshed. Typically it
250 /// will be called once per app start, but may be called more often, if token is invalidated or
251 /// updated. In this method, you should perform operations such as:
253 /// * Uploading the FCM token to your application server, so targeted notifications can be sent.
255 /// * Subscribing to any topics.
256 - (void)messaging:(FIRMessaging *)messaging
257 didReceiveRegistrationToken:(NSString *)fcmToken
258 NS_SWIFT_NAME(messaging(_:didReceiveRegistrationToken:));
260 /// This method is called on iOS 10 devices to handle data messages received via FCM through its
261 /// direct channel (not via APNS). For iOS 9 and below, the FCM data message is delivered via the
262 /// UIApplicationDelegate's -application:didReceiveRemoteNotification: method.
263 - (void)messaging:(FIRMessaging *)messaging
264 didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage
265 NS_SWIFT_NAME(messaging(_:didReceive:))
266 __IOS_AVAILABLE(10.0);
271 * Firebase Messaging lets you reliably deliver messages at no cost.
273 * To send or receive messages, the app must get a
274 * registration token from FIRInstanceID. This token authorizes an
275 * app server to send messages to an app instance.
277 * In order to receive FIRMessaging messages, declare `application:didReceiveRemoteNotification:`.
279 NS_SWIFT_NAME(Messaging)
280 @interface FIRMessaging : NSObject
283 * Delegate to handle FCM token refreshes, and remote data messages received via FCM for devices
284 * running iOS 10 or above.
286 @property(nonatomic, weak, nullable) id<FIRMessagingDelegate> delegate;
289 * When set to `YES`, Firebase Messaging will automatically establish a socket-based, direct
290 * channel to the FCM server. Enable this only if you are sending upstream messages or
291 * receiving non-APNS, data-only messages in foregrounded apps.
294 @property(nonatomic) BOOL shouldEstablishDirectChannel;
297 * Returns `YES` if the direct channel to the FCM server is active, and `NO` otherwise.
299 @property(nonatomic, readonly) BOOL isDirectChannelEstablished;
304 * @return An instance of FIRMessaging.
306 + (instancetype)messaging NS_SWIFT_NAME(messaging());
309 * Unavailable. Use +messaging instead.
311 - (instancetype)init __attribute__((unavailable("Use +messaging instead.")));
316 * This property is used to set the APNS Token received by the application delegate.
318 * FIRMessaging uses method swizzling to ensure that the APNS token is set
319 * automatically. However, if you have disabled swizzling by setting
320 * `FirebaseAppDelegateProxyEnabled` to `NO` in your app's
321 * Info.plist, you should manually set the APNS token in your application
322 * delegate's `-application:didRegisterForRemoteNotificationsWithDeviceToken:`
325 * If you would like to set the type of the APNS token, rather than relying on
326 * automatic detection, see: `-setAPNSToken:type:`.
328 @property(nonatomic, copy, nullable) NSData *APNSToken NS_SWIFT_NAME(apnsToken);
331 * Set APNS token for the application. This APNS token will be used to register
332 * with Firebase Messaging using `FCMToken` or
333 * `tokenWithAuthorizedEntity:scope:options:handler`.
335 * @param apnsToken The APNS token for the application.
336 * @param type The type of APNS token. Debug builds should use
337 * FIRMessagingAPNSTokenTypeSandbox. Alternatively, you can supply
338 * FIRMessagingAPNSTokenTypeUnknown to have the type automatically
339 * detected based on your provisioning profile.
341 - (void)setAPNSToken:(NSData *)apnsToken type:(FIRMessagingAPNSTokenType)type;
343 #pragma mark - FCM Tokens
346 * Is Firebase Messaging token auto generation enabled? If this flag is disabled,
347 * Firebase Messaging will not generate token automatically for message delivery.
349 * If this flag is disabled, Firebase Messaging does not generate new tokens automatically for
350 * message delivery. If this flag is enabled, FCM generates a registration token on application
351 * start when there is no existing valid token. FCM also generates a new token when an existing
354 * This setting is persisted, and is applied on future
355 * invocations of your application. Once explicitly set, it overrides any
356 * settings in your Info.plist.
358 * By default, FCM automatic initialization is enabled. If you need to change the
359 * default (for example, because you want to prompt the user before getting token)
360 * set FirebaseMessagingAutoInitEnabled to false in your application's Info.plist.
362 @property(nonatomic, assign, getter=isAutoInitEnabled) BOOL autoInitEnabled;
365 * The FCM token is used to identify this device so that FCM can send notifications to it.
366 * It is associated with your APNS token when the APNS token is supplied, so that sending
367 * messages to the FCM token will be delivered over APNS.
369 * The FCM token is sometimes refreshed automatically. In your FIRMessaging delegate, the
370 * delegate method `messaging:didReceiveRegistrationToken:` will be called once a token is
371 * available, or has been refreshed. Typically it should be called once per app start, but
372 * may be called more often, if token is invalidated or updated.
374 * Once you have an FCM token, you should send it to your application server, so it can use
375 * the FCM token to send notifications to your device.
377 @property(nonatomic, readonly, nullable) NSString *FCMToken NS_SWIFT_NAME(fcmToken);
381 * Retrieves an FCM registration token for a particular Sender ID. This can be used to allow
382 * multiple senders to send notifications to the same device. By providing a different Sender
383 * ID than your default when fetching a token, you can create a new FCM token which you can
384 * give to a different sender. Both tokens will deliver notifications to your device, and you
385 * can revoke a token when you need to.
387 * This registration token is not cached by FIRMessaging. FIRMessaging should have an APNS
388 * token set before calling this to ensure that notifications can be delivered via APNS using
389 * this FCM token. You may re-retrieve the FCM token once you have the APNS token set, to
390 * associate it with the FCM token. The default FCM token is automatically associated with
391 * the APNS token, if the APNS token data is available.
393 * @param senderID The Sender ID for a particular Firebase project.
394 * @param completion The completion handler to handle the token request.
396 - (void)retrieveFCMTokenForSenderID:(NSString *)senderID
397 completion:(FIRMessagingFCMTokenFetchCompletion)completion
398 NS_SWIFT_NAME(retrieveFCMToken(forSenderID:completion:));
402 * Invalidates an FCM token for a particular Sender ID. That Sender ID cannot no longer send
403 * notifications to that FCM token.
405 * @param senderID The senderID for a particular Firebase project.
406 * @param completion The completion handler to handle the token deletion.
408 - (void)deleteFCMTokenForSenderID:(NSString *)senderID
409 completion:(FIRMessagingDeleteFCMTokenCompletion)completion
410 NS_SWIFT_NAME(deleteFCMToken(forSenderID:completion:));
413 #pragma mark - Connect
416 * Create a FIRMessaging data connection which will be used to send the data notifications
417 * sent by your server. It will also be used to send ACKS and other messages based
418 * on the FIRMessaging ACKS and other messages based on the FIRMessaging protocol.
421 * @param handler The handler to be invoked once the connection is established.
422 * If the connection fails we invoke the handler with an
423 * appropriate error code letting you know why it failed. At
424 * the same time, FIRMessaging performs exponential backoff to retry
425 * establishing a connection and invoke the handler when successful.
427 - (void)connectWithCompletion:(FIRMessagingConnectCompletion)handler
428 NS_SWIFT_NAME(connect(handler:))
429 __deprecated_msg("Please use the shouldEstablishDirectChannel property instead.");
432 * Disconnect the current FIRMessaging data connection. This stops any attempts to
433 * connect to FIRMessaging. Calling this on an already disconnected client is a no-op.
435 * Call this before `teardown` when your app is going to the background.
436 * Since the FIRMessaging connection won't be allowed to live when in the background, it is
437 * prudent to close the connection.
440 __deprecated_msg("Please use the shouldEstablishDirectChannel property instead.");
442 #pragma mark - Topics
445 * Asynchronously subscribes to a topic.
447 * @param topic The name of the topic, for example, @"sports".
449 - (void)subscribeToTopic:(NSString *)topic NS_SWIFT_NAME(subscribe(toTopic:));
452 * Asynchronously subscribe to the provided topic, retrying on failure.
454 * @param topic The topic name to subscribe to, for example, @"sports".
455 * @param completion The completion that is invoked once the subscribe call ends.
456 * In case of success, nil error is returned. Otherwise, an
457 * appropriate error object is returned.
459 - (void)subscribeToTopic:(nonnull NSString *)topic
460 completion:(nullable FIRMessagingTopicOperationCompletion)completion;
463 * Asynchronously unsubscribe from a topic.
465 * @param topic The name of the topic, for example @"sports".
467 - (void)unsubscribeFromTopic:(NSString *)topic NS_SWIFT_NAME(unsubscribe(fromTopic:));
470 * Asynchronously unsubscribe from the provided topic, retrying on failure.
472 * @param topic The topic name to unsubscribe from, for example @"sports".
473 * @param completion The completion that is invoked once the unsubscribe call ends.
474 * In case of success, nil error is returned. Otherwise, an
475 * appropriate error object is returned.
477 - (void)unsubscribeFromTopic:(nonnull NSString *)topic
478 completion:(nullable FIRMessagingTopicOperationCompletion)completion;
480 #pragma mark - Upstream
483 * Sends an upstream ("device to cloud") message.
485 * The message is queued if we don't have an active connection.
486 * You can only use the upstream feature if your FCM implementation
487 * uses the XMPP server protocol.
489 * @param message Key/Value pairs to be sent. Values must be String, any
490 * other type will be ignored.
491 * @param receiver A string identifying the receiver of the message. For FCM
492 * project IDs the value is `SENDER_ID@gcm.googleapis.com`.
493 * @param messageID The ID of the message. This is generated by the application. It
494 * must be unique for each message generated by this application.
495 * It allows error callbacks and debugging, to uniquely identify
497 * @param ttl The time to live for the message. In case we aren't able to
498 * send the message before the TTL expires we will send you a
499 * callback. If 0, we'll attempt to send immediately and return
500 * an error if we're not connected. Otherwise, the message will
501 * be queued. As for server-side messages, we don't return an error
502 * if the message has been dropped because of TTL; this can happen
503 * on the server side, and it would require extra communication.
505 - (void)sendMessage:(NSDictionary *)message
506 to:(NSString *)receiver
507 withMessageID:(NSString *)messageID
508 timeToLive:(int64_t)ttl;
510 #pragma mark - Analytics
513 * Use this to track message delivery and analytics for messages, typically
514 * when you receive a notification in `application:didReceiveRemoteNotification:`.
515 * However, you only need to call this if you set the `FirebaseAppDelegateProxyEnabled`
516 * flag to `NO` in your Info.plist. If `FirebaseAppDelegateProxyEnabled` is either missing
517 * or set to `YES` in your Info.plist, the library will call this automatically.
519 * @param message The downstream message received by the application.
521 * @return Information about the downstream message.
523 - (FIRMessagingMessageInfo *)appDidReceiveMessage:(NSDictionary *)message;
527 NS_ASSUME_NONNULL_END