iOS移动应用程序中的推送通知

+ Shubaham Jain

iOS移动应用程序中的推送通知

对于iOS应用,您可以通过以下两种方式实施Firebase Cloud Messaging:

  • 通过Firebase Cloud Messaging APNs界面接收最大4KB的基本推送通知消息。
  • 在前台应用程序中向上游发送消息和/或接收高达4KB的下游数据有效载荷。

将Firebase添加到您的iOS项目

对于iOS客户端应用程序,您可以通过两种互补的方式实施Firebase Cloud Messaging:

  • 通过Firebase Cloud Messaging APNs界面接收最大4KB的基本推送消息。
  • 在前台应用程序中向上游发送消息和/或接收高达4KB的下游数据有效载荷。

将Firebase添加到您的iOS项目

先决条件

在开始之前,您需要在环境中进行一些设置:

  • Xcode 8.0或更高版本
  • 针对iOS 8或更高版本的Xcode项目
  • Swift项目必须使用Swift 3.0或更高版本
  • 您的应用程序的捆绑标识符
  • CocoaPods 1.2.0或更高版本
  • 对于云消息传递:
  • 物理iOS设备
  • 您的Apple Developer帐户的Apple Push Notification身份验证密钥
  • 在Xcode中,在“ 应用”>“功能”中启用“推送通知”

在Mac机器上安装Cocoapods的步骤:

步骤1:如果您的计算机上未安装cocoapods,请首先在终端sudo gem install cocoapods上使用以下命令将其安装在计算机上

步骤2:将汇出至

导出PATH = $ PATH:/ Library / Ruby / bin

步骤3:检查您在计算机上安装的cocoapods的版本

Pod-版本

步骤4 :打开终端,使用以下命令转到您的项目目录

$ cd /用户/ xyz /文档/ FireBaseOne / FirebaseDemo

步骤5 :初始化Pod

荚初始化

使用以下命令打开pod文件

打开Podfile

并在podfile中添加以下内容

‘Firebase’,’〜> 3.0’

‘Firebase / Messaging’,’〜> 3.0’

步骤6 :安装吊舱

吊舱安装

步骤7 :现在,使用以下命令打开xcworkspace

打开your-project.xcworkspace

第8步 :现在转到firebase控制台并创建一个新项目

填写应用程序名称和国家/地区名称,然后将应用程序的捆绑标识符添加到相应的文本字段。

现在下载配置文件,并将GoogleService-info.plist文件添加到xcode项目中

使用命令行安装我们已经安装的Pod

在您的应用中设置Firebase

您将需要在您的应用程序中添加Firebase初始化代码。在appdelegate类中导入firebase模块,并配置一个共享实例,如下所示AppDelegate.h

#import  
#import
 @interface AppDelegate : UIResponder <UIApplicationDelegate, 
FIRMessagingDelegate,
UNUserNotificationCenterDelegate>
{
 // conform the firebase delegate as above 
 } 
@end

AppDelegate.m

 @import Firebase; 
@import UserNotifications;
@import FirebaseMessaging;

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{
  [FIRApp configure]; 
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  [UNUserNotificationCenter currentNotificationCenter].delegate = self; 
[FIRMessaging messaging].delegate = self;
 #endif 
 [self registerRemoteNotification]; 
 [[NSNotificationCenter defaultCenter] 
addObserver:self selector:@selector(tokenRefreshCallback:)
name:kFIRInstanceIDTokenRefreshNotification object:nil ];
 } 

 - (void)applicationDidEnterBackground:(UIApplication *)application 
{
[[FIRMessaging messaging] setShouldEstablishDirectChannel:NO];
}
 - (void)applicationDidBecomeActive:(UIApplication *)application 
{
// jump to the custom connectToFirebase method defination
  [self connetToFireBase]; 
}

 -(void)registerRemoteNotification 
{
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
UIUserNotificationType allNotificationTypes =(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
else
{
// iOS 10 or later
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert| UNAuthorizationOptionSound| UNAuthorizationOptionBadge;
  [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { 
NSLog(@"Error in push registration = %@",error);
}];
[FIRMessaging messaging].delegate = self;
}
  [[UIApplication sharedApplication] registerForRemoteNotifications]; 
}
 - (void)application:(UIApplication *)application 
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
  NSLog(@"device Token = %@",deviceToken); 
[FIRMessaging messaging].APNSToken = deviceToken;
}
 - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { 
if (error.code == 3010) {
NSLog(@"Push notifications are not supported in the iOS Simulator.");
}
else {
NSLog(@"application:didFailToRegisterForRemoteNotificationsWithError: %@", error);
}
}

 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { 
  [[UIApplication sharedApplication] registerForRemoteNotifications]; 
  if ( application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground ) 
{
// opened Application from a push notification when the app was on background or inactiva state
[self callCustomMethod];
  } 
}

 -(void)application:(UIApplication *)application didReceiveRemoteNotification: 
(NSDictionary *)userInfo fetchCompletionHandler:(void (^)
(UIBackgroundFetchResult))completionHandler {
NSLog(@"Push iOS9 = %@", userInfo);
  [[FIRMessaging messaging] appDidReceiveMessage:userInfo]; 
if ( application.applicationState == UIApplicationStateInactive ||
application.applicationState == UIApplicationStateBackground)
{
// opened Application from a push notification when
the app was on background or inactiva state
[self callCustomMetod];
}
  completionHandler(UIBackgroundFetchResultNewData | UIBackgroundFetchResultNoData | UIBackgroundFetchResultFailed); 
}

 /* 
  Push Notification will be shown while app is in foregroung from iOS 10 Onwards 
  First Include #import  
second Include
 */ 
- (void)userNotificationCenter:(UNUserNotificationCenter* )center
willPresentNotification:(UNNotification* )notification
withCompletionHandler:(void (^)
(UNNotificationPresentationOptions options))completionHandler {
NSLog(@"Push iOS10 (Foreground) = %@",notification.request.content.userInfo);
completionHandler(UNNotificationPresentationOptionAlert |
UNNotificationPresentationOptionBadge |
UNNotificationPresentationOptionSound);
 } 
 /* 
Call this method when user want to open app while in
foreground on tapping push notification
*/

 - (void)userNotificationCenter:(UNUserNotificationCenter *)center 
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)())completionHandler
{
NSLog(@"Push iOS10 (Background/Closed) = %@", response.notification.request.content.userInfo);
completionHandler(UNNotificationPresentationOptionAlert |
UNNotificationPresentationOptionBadge |
UNNotificationPresentationOptionSound);
 } 
-(void)tokenRefreshCallback:(NSNotification *)notification{
NSString * refreshedToken = [[FIRInstanceID instanceID]token];
NSLog(@"refresh Token is : %@",refreshedToken);
[self connetToFireBase];

}
 -(void)connetToFireBase 
{
[[FIRMessaging messaging] setShouldEstablishDirectChannel:YES];
NSLog((@"Connected To Firebase"));
}

完成上述工作之后,您就完成了Xcode上的编码部分。

使用FCM Firebase云消息传递配置APNs APNs界面使用Apple Push Notification Services将最大4 KB的消息发送到您的应用程序,包括当应用程序处于后台状态时。 要启用通过APN发送推送通知,您需要

  1. Apple开发人员帐户的推送通知身份验证密钥。Firebase使用此令牌在应用程序中感知推送通知。
  2. 该应用程序ID的配置文件。

创建身份验证密钥:

  1. 转到您的开发者帐户,然后转到证书,标识符和配置文件,然后在密钥下,选择全部
  2. 点击添加按钮(+)
  3. 输入身份验证密钥的描述
  4. 在关键服务下,选中“ APNs”复选框,然后单击“继续”。
  5. 单击确认并下载。保存您的密钥,这是一次下载,无法检索此密钥。

创建应用程序ID:应用程序ID是唯一标识应用程序的标识符

  1. 转到苹果开发者帐户
  2. 转到证书,标识符和配置文件
  3. 在下拉菜单中,选择“ iOS应用”并导航标识符“应用ID”
  4. 点击+按钮创建新的应用ID

创建新的应用程序ID

  1. 输入您的应用ID的名称
  2. 选择应用程序ID前缀
  3. 在“应用ID后缀”部分中,选择“ 显式应用ID”,然后输入您的捆绑包标识符。 捆绑包标识符的值应与您在应用程序info.plist中使用的值和用于获取FCM配置的值相匹配。
  1. 在“应用程序服务”部分中,选中“ 推送通知”选项
  1. 单击继续,并检查所有输入是否正确。
  2. 点击注册以创建应用ID。

创建配置文件

  1. 转到苹果开发者帐户
  2. 转到证书,标识符和配置文件
  3. 在下拉菜单中选择ios应用,然后转到“供应配置文件”并全选
  4. 单击+图标创建配置文件
  5. 选择iOS App Development作为用于开发目的的供应类型,单击继续
  6. 在下拉列表中选择要使用的应用程序ID ,然后单击继续
  7. 选择应用程序ID的iOS开发证书,然后单击继续
  8. 选择要包括配置文件的iOS设备,单击继续
  9. 提供配置文件的名称,单击生成
  10. 单击下载以在Mac上保存配置文件
  11. 双击配置文件进行安装。

如果您喜欢这篇文章,请在Medium上关注我。 当我有新事物要分享时。 这是找出我何时撰写更多此类文章的最佳方法。

iOSBlogger:https://zenshubham.blogspot.com/2018/03/pushnotification.html

谢谢