FIRMessaging.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /*
  2. * Copyright 2017 Google
  3. *
  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
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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.
  15. */
  16. #import <Foundation/Foundation.h>
  17. /**
  18. * @related FIRMessaging
  19. *
  20. * The completion handler invoked when the registration token returns.
  21. * If the call fails we return the appropriate `error code`, described by
  22. * `FIRMessagingError`.
  23. *
  24. * @param FCMToken The valid registration token returned by FCM.
  25. * @param error The error describing why a token request failed. The error code
  26. * will match a value from the FIRMessagingError enumeration.
  27. */
  28. typedef void(^FIRMessagingFCMTokenFetchCompletion)(NSString * _Nullable FCMToken,
  29. NSError * _Nullable error)
  30. NS_SWIFT_NAME(MessagingFCMTokenFetchCompletion);
  31. /**
  32. * @related FIRMessaging
  33. *
  34. * The completion handler invoked when the registration token deletion request is
  35. * completed. If the call fails we return the appropriate `error code`, described
  36. * by `FIRMessagingError`.
  37. *
  38. * @param error The error describing why a token deletion failed. The error code
  39. * will match a value from the FIRMessagingError enumeration.
  40. */
  41. typedef void(^FIRMessagingDeleteFCMTokenCompletion)(NSError * _Nullable error)
  42. NS_SWIFT_NAME(MessagingDeleteFCMTokenCompletion);
  43. /**
  44. * The completion handler invoked once the data connection with FIRMessaging is
  45. * established. The data connection is used to send a continous stream of
  46. * data and all the FIRMessaging data notifications arrive through this connection.
  47. * Once the connection is established we invoke the callback with `nil` error.
  48. * Correspondingly if we get an error while trying to establish a connection
  49. * we invoke the handler with an appropriate error object and do an
  50. * exponential backoff to try and connect again unless successful.
  51. *
  52. * @param error The error object if any describing why the data connection
  53. * to FIRMessaging failed.
  54. */
  55. typedef void(^FIRMessagingConnectCompletion)(NSError * __nullable error)
  56. NS_SWIFT_NAME(MessagingConnectCompletion)
  57. __deprecated_msg("Please listen for the FIRMessagingConnectionStateChangedNotification "
  58. "NSNotification instead.");
  59. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  60. /**
  61. * Notification sent when the upstream message has been delivered
  62. * successfully to the server. The notification object will be the messageID
  63. * of the successfully delivered message.
  64. */
  65. FOUNDATION_EXPORT const NSNotificationName __nonnull FIRMessagingSendSuccessNotification
  66. NS_SWIFT_NAME(MessagingSendSuccess);
  67. /**
  68. * Notification sent when the upstream message was failed to be sent to the
  69. * server. The notification object will be the messageID of the failed
  70. * message. The userInfo dictionary will contain the relevant error
  71. * information for the failure.
  72. */
  73. FOUNDATION_EXPORT const NSNotificationName __nonnull FIRMessagingSendErrorNotification
  74. NS_SWIFT_NAME(MessagingSendError);
  75. /**
  76. * Notification sent when the Firebase messaging server deletes pending
  77. * messages due to exceeded storage limits. This may occur, for example, when
  78. * the device cannot be reached for an extended period of time.
  79. *
  80. * It is recommended to retrieve any missing messages directly from the
  81. * server.
  82. */
  83. FOUNDATION_EXPORT const NSNotificationName __nonnull FIRMessagingMessagesDeletedNotification
  84. NS_SWIFT_NAME(MessagingMessagesDeleted);
  85. /**
  86. * Notification sent when Firebase Messaging establishes or disconnects from
  87. * an FCM socket connection. You can query the connection state in this
  88. * notification by checking the `isDirectChannelEstablished` property of FIRMessaging.
  89. */
  90. FOUNDATION_EXPORT const NSNotificationName __nonnull FIRMessagingConnectionStateChangedNotification
  91. NS_SWIFT_NAME(MessagingConnectionStateChanged);
  92. /**
  93. * Notification sent when the FCM registration token has been refreshed. Please use the
  94. * FIRMessaging delegate method `messaging:didReceiveRegistrationToken:` to receive current and
  95. * updated tokens.
  96. */
  97. FOUNDATION_EXPORT const NSNotificationName __nonnull
  98. FIRMessagingRegistrationTokenRefreshedNotification
  99. NS_SWIFT_NAME(MessagingRegistrationTokenRefreshed);
  100. #else
  101. /**
  102. * Notification sent when the upstream message has been delivered
  103. * successfully to the server. The notification object will be the messageID
  104. * of the successfully delivered message.
  105. */
  106. FOUNDATION_EXPORT NSString * __nonnull const FIRMessagingSendSuccessNotification
  107. NS_SWIFT_NAME(MessagingSendSuccessNotification);
  108. /**
  109. * Notification sent when the upstream message was failed to be sent to the
  110. * server. The notification object will be the messageID of the failed
  111. * message. The userInfo dictionary will contain the relevant error
  112. * information for the failure.
  113. */
  114. FOUNDATION_EXPORT NSString * __nonnull const FIRMessagingSendErrorNotification
  115. NS_SWIFT_NAME(MessagingSendErrorNotification);
  116. /**
  117. * Notification sent when the Firebase messaging server deletes pending
  118. * messages due to exceeded storage limits. This may occur, for example, when
  119. * the device cannot be reached for an extended period of time.
  120. *
  121. * It is recommended to retrieve any missing messages directly from the
  122. * server.
  123. */
  124. FOUNDATION_EXPORT NSString * __nonnull const FIRMessagingMessagesDeletedNotification
  125. NS_SWIFT_NAME(MessagingMessagesDeletedNotification);
  126. /**
  127. * Notification sent when Firebase Messaging establishes or disconnects from
  128. * an FCM socket connection. You can query the connection state in this
  129. * notification by checking the `isDirectChannelEstablished` property of FIRMessaging.
  130. */
  131. FOUNDATION_EXPORT NSString * __nonnull const FIRMessagingConnectionStateChangedNotification
  132. NS_SWIFT_NAME(MessagingConnectionStateChangedNotification);
  133. /**
  134. * Notification sent when the FCM registration token has been refreshed. Please use the
  135. * FIRMessaging delegate method `messaging:didReceiveRegistrationToken:` to receive current and
  136. * updated tokens.
  137. */
  138. FOUNDATION_EXPORT NSString * __nonnull const FIRMessagingRegistrationTokenRefreshedNotification
  139. NS_SWIFT_NAME(MessagingRegistrationTokenRefreshedNotification);
  140. #endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  141. /**
  142. * @enum FIRMessagingError
  143. */
  144. typedef NS_ENUM(NSUInteger, FIRMessagingError) {
  145. /// Unknown error.
  146. FIRMessagingErrorUnknown = 0,
  147. /// FIRMessaging couldn't validate request from this client.
  148. FIRMessagingErrorAuthentication = 1,
  149. /// InstanceID service cannot be accessed.
  150. FIRMessagingErrorNoAccess = 2,
  151. /// Request to InstanceID backend timed out.
  152. FIRMessagingErrorTimeout = 3,
  153. /// No network available to reach the servers.
  154. FIRMessagingErrorNetwork = 4,
  155. /// Another similar operation in progress, bailing this one.
  156. FIRMessagingErrorOperationInProgress = 5,
  157. /// Some parameters of the request were invalid.
  158. FIRMessagingErrorInvalidRequest = 7,
  159. } NS_SWIFT_NAME(MessagingError);
  160. /// Status for the downstream message received by the app.
  161. typedef NS_ENUM(NSInteger, FIRMessagingMessageStatus) {
  162. /// Unknown status.
  163. FIRMessagingMessageStatusUnknown,
  164. /// New downstream message received by the app.
  165. FIRMessagingMessageStatusNew,
  166. } NS_SWIFT_NAME(MessagingMessageStatus);
  167. /**
  168. * The APNS token type for the app. If the token type is set to `UNKNOWN`
  169. * Firebase Messaging will implicitly try to figure out what the actual token type
  170. * is from the provisioning profile.
  171. * Unless you really need to specify the type, you should use the `APNSToken`
  172. * property instead.
  173. */
  174. typedef NS_ENUM(NSInteger, FIRMessagingAPNSTokenType) {
  175. /// Unknown token type.
  176. FIRMessagingAPNSTokenTypeUnknown,
  177. /// Sandbox token type.
  178. FIRMessagingAPNSTokenTypeSandbox,
  179. /// Production token type.
  180. FIRMessagingAPNSTokenTypeProd,
  181. } NS_SWIFT_NAME(MessagingAPNSTokenType);
  182. /// Information about a downstream message received by the app.
  183. NS_SWIFT_NAME(MessagingMessageInfo)
  184. @interface FIRMessagingMessageInfo : NSObject
  185. /// The status of the downstream message
  186. @property(nonatomic, readonly, assign) FIRMessagingMessageStatus status;
  187. @end
  188. /**
  189. * A remote data message received by the app via FCM (not just the APNs interface).
  190. *
  191. * This is only for devices running iOS 10 or above. To support devices running iOS 9 or below, use
  192. * the local and remote notifications handlers defined in UIApplicationDelegate protocol.
  193. */
  194. NS_SWIFT_NAME(MessagingRemoteMessage)
  195. @interface FIRMessagingRemoteMessage : NSObject
  196. /// The downstream message received by the application.
  197. @property(nonatomic, readonly, strong, nonnull) NSDictionary *appData;
  198. @end
  199. @class FIRMessaging;
  200. /**
  201. * A protocol to handle events from FCM for devices running iOS 10 or above.
  202. *
  203. * To support devices running iOS 9 or below, use the local and remote notifications handlers
  204. * defined in UIApplicationDelegate protocol.
  205. */
  206. NS_SWIFT_NAME(MessagingDelegate)
  207. @protocol FIRMessagingDelegate <NSObject>
  208. @optional
  209. /// This method will be called once a token is available, or has been refreshed. Typically it
  210. /// will be called once per app start, but may be called more often, if token is invalidated or
  211. /// updated. In this method, you should perform operations such as:
  212. ///
  213. /// * Uploading the FCM token to your application server, so targeted notifications can be sent.
  214. ///
  215. /// * Subscribing to any topics.
  216. - (void)messaging:(nonnull FIRMessaging *)messaging
  217. didReceiveRegistrationToken:(nonnull NSString *)fcmToken
  218. NS_SWIFT_NAME(messaging(_:didReceiveRegistrationToken:));
  219. /// This method will be called whenever FCM receives a new, default FCM token for your
  220. /// Firebase project's Sender ID. This method is deprecated. Please use
  221. /// `messaging:didReceiveRegistrationToken:`.
  222. - (void)messaging:(nonnull FIRMessaging *)messaging
  223. didRefreshRegistrationToken:(nonnull NSString *)fcmToken
  224. NS_SWIFT_NAME(messaging(_:didRefreshRegistrationToken:))
  225. __deprecated_msg("Please use messaging:didReceiveRegistrationToken:, which is called for both \
  226. current and refreshed tokens.");
  227. /// This method is called on iOS 10 devices to handle data messages received via FCM through its
  228. /// direct channel (not via APNS). For iOS 9 and below, the FCM data message is delivered via the
  229. /// UIApplicationDelegate's -application:didReceiveRemoteNotification: method.
  230. - (void)messaging:(nonnull FIRMessaging *)messaging
  231. didReceiveMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage
  232. NS_SWIFT_NAME(messaging(_:didReceive:))
  233. __IOS_AVAILABLE(10.0);
  234. /// The callback to handle data message received via FCM for devices running iOS 10 or above.
  235. - (void)applicationReceivedRemoteMessage:(nonnull FIRMessagingRemoteMessage *)remoteMessage
  236. NS_SWIFT_NAME(application(received:))
  237. __deprecated_msg("Use FIRMessagingDelegate’s -messaging:didReceiveMessage:");
  238. @end
  239. /**
  240. * Firebase Messaging lets you reliably deliver messages at no cost.
  241. *
  242. * To send or receive messages, the app must get a
  243. * registration token from FIRInstanceID. This token authorizes an
  244. * app server to send messages to an app instance.
  245. *
  246. * In order to receive FIRMessaging messages, declare `application:didReceiveRemoteNotification:`.
  247. */
  248. NS_SWIFT_NAME(Messaging)
  249. @interface FIRMessaging : NSObject
  250. /**
  251. * Delegate to handle FCM token refreshes, and remote data messages received via FCM for devices
  252. * running iOS 10 or above.
  253. */
  254. @property(nonatomic, weak, nullable) id<FIRMessagingDelegate> delegate;
  255. /**
  256. * Delegate to handle remote data messages received via FCM for devices running iOS 10 or above.
  257. */
  258. @property(nonatomic, weak, nullable) id<FIRMessagingDelegate> remoteMessageDelegate
  259. __deprecated_msg("Use 'delegate' property");
  260. /**
  261. * When set to `YES`, Firebase Messaging will automatically establish a socket-based, direct
  262. * channel to the FCM server. Enable this only if you are sending upstream messages or
  263. * receiving non-APNS, data-only messages in foregrounded apps.
  264. * Default is `NO`.
  265. */
  266. @property(nonatomic) BOOL shouldEstablishDirectChannel;
  267. /**
  268. * Returns `YES` if the direct channel to the FCM server is active, and `NO` otherwise.
  269. */
  270. @property(nonatomic, readonly) BOOL isDirectChannelEstablished;
  271. /**
  272. * FIRMessaging
  273. *
  274. * @return An instance of FIRMessaging.
  275. */
  276. + (nonnull instancetype)messaging NS_SWIFT_NAME(messaging());
  277. /**
  278. * Unavailable. Use +messaging instead.
  279. */
  280. - (nonnull instancetype)init __attribute__((unavailable("Use +messaging instead.")));
  281. #pragma mark - APNS
  282. /**
  283. * This property is used to set the APNS Token received by the application delegate.
  284. *
  285. * FIRMessaging uses method swizzling to ensure that the APNS token is set
  286. * automatically. However, if you have disabled swizzling by setting
  287. * `FirebaseAppDelegateProxyEnabled` to `NO` in your app's
  288. * Info.plist, you should manually set the APNS token in your application
  289. * delegate's `-application:didRegisterForRemoteNotificationsWithDeviceToken:`
  290. * method.
  291. *
  292. * If you would like to set the type of the APNS token, rather than relying on
  293. * automatic detection, see: `-setAPNSToken:type:`.
  294. */
  295. @property(nonatomic, copy, nullable) NSData *APNSToken NS_SWIFT_NAME(apnsToken);
  296. /**
  297. * Set APNS token for the application. This APNS token will be used to register
  298. * with Firebase Messaging using `FCMToken` or
  299. * `tokenWithAuthorizedEntity:scope:options:handler`.
  300. *
  301. * @param apnsToken The APNS token for the application.
  302. * @param type The type of APNS token. Debug builds should use
  303. * FIRMessagingAPNSTokenTypeSandbox. Alternatively, you can supply
  304. * FIRMessagingAPNSTokenTypeUnknown to have the type automatically
  305. * detected based on your provisioning profile.
  306. */
  307. - (void)setAPNSToken:(nonnull NSData *)apnsToken type:(FIRMessagingAPNSTokenType)type;
  308. #pragma mark - FCM Tokens
  309. /**
  310. * The FCM token is used to identify this device so that FCM can send notifications to it.
  311. * It is associated with your APNS token when the APNS token is supplied, so that sending
  312. * messages to the FCM token will be delivered over APNS.
  313. *
  314. * The FCM token is sometimes refreshed automatically. In your FIRMessaging delegate, the
  315. * delegate method `messaging:didReceiveRegistrationToken:` will be called once a token is
  316. * available, or has been refreshed. Typically it should be called once per app start, but
  317. * may be called more often, if token is invalidated or updated.
  318. *
  319. * Once you have an FCM token, you should send it to your application server, so it can use
  320. * the FCM token to send notifications to your device.
  321. */
  322. @property(nonatomic, readonly, nullable) NSString *FCMToken NS_SWIFT_NAME(fcmToken);
  323. /**
  324. * Retrieves an FCM registration token for a particular Sender ID. This can be used to allow
  325. * multiple senders to send notifications to the same device. By providing a different Sender
  326. * ID than your default when fetching a token, you can create a new FCM token which you can
  327. * give to a different sender. Both tokens will deliver notifications to your device, and you
  328. * can revoke a token when you need to.
  329. *
  330. * This registration token is not cached by FIRMessaging. FIRMessaging should have an APNS
  331. * token set before calling this to ensure that notifications can be delivered via APNS using
  332. * this FCM token. You may re-retrieve the FCM token once you have the APNS token set, to
  333. * associate it with the FCM token. The default FCM token is automatically associated with
  334. * the APNS token, if the APNS token data is available.
  335. *
  336. * @param senderID The Sender ID for a particular Firebase project.
  337. * @param completion The completion handler to handle the token request.
  338. */
  339. - (void)retrieveFCMTokenForSenderID:(nonnull NSString *)senderID
  340. completion:(nonnull FIRMessagingFCMTokenFetchCompletion)completion
  341. NS_SWIFT_NAME(retrieveFCMToken(forSenderID:completion:));
  342. /**
  343. * Invalidates an FCM token for a particular Sender ID. That Sender ID cannot no longer send
  344. * notifications to that FCM token.
  345. *
  346. * @param senderID The senderID for a particular Firebase project.
  347. * @param completion The completion handler to handle the token deletion.
  348. */
  349. - (void)deleteFCMTokenForSenderID:(nonnull NSString *)senderID
  350. completion:(nonnull FIRMessagingDeleteFCMTokenCompletion)completion
  351. NS_SWIFT_NAME(deleteFCMToken(forSenderID:completion:));
  352. #pragma mark - Connect
  353. /**
  354. * Create a FIRMessaging data connection which will be used to send the data notifications
  355. * sent by your server. It will also be used to send ACKS and other messages based
  356. * on the FIRMessaging ACKS and other messages based on the FIRMessaging protocol.
  357. *
  358. *
  359. * @param handler The handler to be invoked once the connection is established.
  360. * If the connection fails we invoke the handler with an
  361. * appropriate error code letting you know why it failed. At
  362. * the same time, FIRMessaging performs exponential backoff to retry
  363. * establishing a connection and invoke the handler when successful.
  364. */
  365. - (void)connectWithCompletion:(nonnull FIRMessagingConnectCompletion)handler
  366. NS_SWIFT_NAME(connect(handler:))
  367. __deprecated_msg("Please use the shouldEstablishDirectChannel property instead.");
  368. /**
  369. * Disconnect the current FIRMessaging data connection. This stops any attempts to
  370. * connect to FIRMessaging. Calling this on an already disconnected client is a no-op.
  371. *
  372. * Call this before `teardown` when your app is going to the background.
  373. * Since the FIRMessaging connection won't be allowed to live when in the background, it is
  374. * prudent to close the connection.
  375. */
  376. - (void)disconnect
  377. __deprecated_msg("Please use the shouldEstablishDirectChannel property instead.");
  378. #pragma mark - Topics
  379. /**
  380. * Asynchronously subscribes to a topic.
  381. *
  382. * @param topic The name of the topic, for example, @"sports".
  383. */
  384. - (void)subscribeToTopic:(nonnull NSString *)topic NS_SWIFT_NAME(subscribe(toTopic:));
  385. /**
  386. * Asynchronously unsubscribe from a topic.
  387. *
  388. * @param topic The name of the topic, for example @"sports".
  389. */
  390. - (void)unsubscribeFromTopic:(nonnull NSString *)topic NS_SWIFT_NAME(unsubscribe(fromTopic:));
  391. #pragma mark - Upstream
  392. /**
  393. * Sends an upstream ("device to cloud") message.
  394. *
  395. * The message is queued if we don't have an active connection.
  396. * You can only use the upstream feature if your FCM implementation
  397. * uses the XMPP server protocol.
  398. *
  399. * @param message Key/Value pairs to be sent. Values must be String, any
  400. * other type will be ignored.
  401. * @param receiver A string identifying the receiver of the message. For FCM
  402. * project IDs the value is `SENDER_ID@gcm.googleapis.com`.
  403. * @param messageID The ID of the message. This is generated by the application. It
  404. * must be unique for each message generated by this application.
  405. * It allows error callbacks and debugging, to uniquely identify
  406. * each message.
  407. * @param ttl The time to live for the message. In case we aren't able to
  408. * send the message before the TTL expires we will send you a
  409. * callback. If 0, we'll attempt to send immediately and return
  410. * an error if we're not connected. Otherwise, the message will
  411. * be queued. As for server-side messages, we don't return an error
  412. * if the message has been dropped because of TTL; this can happen
  413. * on the server side, and it would require extra communication.
  414. */
  415. - (void)sendMessage:(nonnull NSDictionary *)message
  416. to:(nonnull NSString *)receiver
  417. withMessageID:(nonnull NSString *)messageID
  418. timeToLive:(int64_t)ttl;
  419. #pragma mark - Analytics
  420. /**
  421. * Use this to track message delivery and analytics for messages, typically
  422. * when you receive a notification in `application:didReceiveRemoteNotification:`.
  423. * However, you only need to call this if you set the `FirebaseAppDelegateProxyEnabled`
  424. * flag to `NO` in your Info.plist. If `FirebaseAppDelegateProxyEnabled` is either missing
  425. * or set to `YES` in your Info.plist, the library will call this automatically.
  426. *
  427. * @param message The downstream message received by the application.
  428. *
  429. * @return Information about the downstream message.
  430. */
  431. - (nonnull FIRMessagingMessageInfo *)appDidReceiveMessage:(nonnull NSDictionary *)message;
  432. @end