You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

527 lines
22 KiB

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