xcode 如何在 iOS 应用程序上实现 Apple 推送通知服务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10515468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I implement Apple Push Notification Service on iOS Application?
提问by Musthafa
Is there any sample project showing how to integrate APNS
on IPhone
, and how to get deviceToken?
有没有说明如何整合所有样本项目APNS
上IPhone
,以及如何获得deviceToken?
回答by David Ben Ari
there are a few simple steps you need to follow:
您需要遵循几个简单的步骤:
in your app delegate's didFinishLaunchingWithOptions you should register for remote notifications. notice that apple's documentations suggests to register each time the app runs since the token may change from time to time. you do this by calling:
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
after registering for remote notifications a method in your app delegate will be called which had been passed the token, you need to implement this method in your app delegate and send the token to your server (that will send you notifications). the method will look like this:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{ NSLog(@"device token is: %@",deviceToken); [server sendToken:deviceToken]; }
在您的应用程序委托的 didFinishLaunchingWithOptions 中,您应该注册远程通知。请注意,Apple 的文档建议在每次应用程序运行时进行注册,因为令牌可能会不时更改。您可以通过以下方式执行此操作:
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
注册远程通知后,将调用已传递令牌的应用程序委托中的方法,您需要在应用程序委托中实现此方法并将令牌发送到您的服务器(这将向您发送通知)。该方法将如下所示:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{ NSLog(@"device token is: %@",deviceToken); [server sendToken:deviceToken]; }
you should also implement this as well:
你也应该实现这一点:
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{}
you need to handle notifications once you get them. there are few different scenarios in which you handle received notifications (the app is in the background or foreground etc.), the method that handles a notification if the app is in the foreground when you receive it should be implemented in the app delegate. this is it:
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{ NSLog(@"received notification"); //handle the notification here }
收到通知后,您需要处理通知。处理收到的通知的场景很少(应用程序在后台或前台等),如果应用程序在前台接收通知时处理通知的方法应该在应用程序委托中实现。就是这个:
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{ NSLog(@"received notification"); //handle the notification here }
to learn more about the userInfo structure and cover all the different scenarios read carefully http://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/ApplePushService/ApplePushService.html. this was just the gist of things :)
要了解有关 userInfo 结构的更多信息并涵盖所有不同的场景,请仔细阅读http://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/ApplePushService/ApplePushService.html。这只是事情的要点:)
回答by Mannam Brahmam
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Register for Push Notitications, if running on iOS 8
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}else{
[application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}
return YES;
}
#pragma mark
#pragma mark -- Push Notification Delegate Methods
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings: (UIUserNotificationSettings *)notificationSettings{
//register to receive notifications
[application registerForRemoteNotifications];
}
-(void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
// Prepare the Device Token for Registration (remove spaces and < >)
NSString* devToken = [[[[deviceToken description]
stringByReplacingOccurrencesOfString:@"<"withString:@""]
stringByReplacingOccurrencesOfString:@">" withString:@""]
stringByReplacingOccurrencesOfString: @" " withString: @""];
NSLog(@"My token is: %@", devToken);
}
-(void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{
// NSLog(@"Failed to get token, error: %@", error);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
NSLog(@"%s..userInfo=%@",__FUNCTION__,userInfo);
/**
* Dump your code here according to your requirement after receiving push
*/
}
回答by Krunal
Here is brief document about - How to enable and send push notification in iOS.
这是关于 - 如何在 iOS 中启用和发送推送通知的简短文档。
Enabling Push Notifications
启用推送通知
The first step in setting up push notifications is enabling the feature within Xcode 8 for your app. Simply go to the project editor for your target and then click on the Capabilities tab. Look for Push Notifications and toggle its value to ON:
设置推送通知的第一步是在 Xcode 8 中为您的应用启用该功能。只需转到目标的项目编辑器,然后单击“功能”选项卡。查找 Push Notifications 并将其值切换为 ON:
Toggle Capability
切换能力
Xcode should display two checkmarks indicating that the capability was successfully enabled. Behind the scenes, Xcode creates an App ID in the Developer Center and enables the Push Notifications service for your app.
Xcode 应显示两个复选标记,表明该功能已成功启用。在幕后,Xcode 在开发人员中心创建一个 App ID 并为您的应用启用推送通知服务。
Registering Devices
注册设备
Devices need to be uniquely identified to receive push notifications.
需要唯一标识设备才能接收推送通知。
Every device that installs your app is assigned a unique device token by APNs that you can use to push it at any given time. Once the device has been assigned a unique token, it should be persisted in your backend database.
APNs 为安装您的应用程序的每台设备分配了一个唯一的设备令牌,您可以使用它在任何给定时间推送它。一旦为设备分配了唯一的令牌,它就应该保存在您的后端数据库中。
A sample device token looks like this:
示例设备令牌如下所示:
5810F4C8C2AF5F7 F7 D6AF71A 22745D0FB50DED 665E0E882 BC5370D9CF0A F19E16
To request a device token for the current device, open AppDelegate.swift and add the following to the didFinishLaunchingWithOptions callback function, before the return statement:
要为当前设备请求设备令牌,请打开 AppDelegate.swift 并将以下内容添加到 didFinishLaunchingWithOptions 回调函数中,在 return 语句之前:
// iOS 10 support
if #available(iOS 10, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
application.registerForRemoteNotifications()
}
// iOS 9 support
else if #available(iOS 9, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 8 support
else if #available(iOS 8, *) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
// iOS 7 support
else {
application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}
In iOS 10, a new framework called UserNotifications was introduced and must be imported in order to access the UNUserNotificationCenter class.
在 iOS 10 中,引入了一个名为 UserNotifications 的新框架,必须导入该框架才能访问 UNUserNotificationCenter 类。
Add the following import statement to the top of AppDelegate.swift:
将以下导入语句添加到 AppDelegate.swift 的顶部:
import UserNotifications
Next, go to the project editor for your target, and in the General tab, look for the Linked Frameworks and Libraries section.
接下来,转到目标的项目编辑器,在 General 选项卡中,查找 Linked Frameworks and Libraries 部分。
Click + and select UserNotifications.framework:
单击 + 并选择 UserNotifications.framework:
Next, add the following callbacks in AppDelegate.swift which will be invoked when APNs has either successfully registered or failed registering the device to receive notifications:
接下来,在 AppDelegate.swift 中添加以下回调,当 APNs 已成功注册或未能注册设备以接收通知时,将调用该回调:
// Called when APNs has assigned the device a unique token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Convert token to string
let deviceTokenString = deviceToken.reduce("", {// Push notification received
func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
// Print notification payload data
print("Push notification received: \(data)")
}
+ String(format: "%02X", )})
// Print it to console
print("APNs device token: \(deviceTokenString)")
// Persist it in your backend in case it's new
}
// Called when APNs failed to register the device for push notifications
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// Print the error to console (you should alert the user that registration failed)
print("APNs registration failed: \(error)")
}
It's up to you to implement logic that will persist the token in your application backend. Later in this guide, your backend server will connect to APNs and send push notifications by providing this very same device token to indicate which device(s) should receive the notification.
由您来实现将令牌保留在您的应用程序后端的逻辑。在本指南的后面,您的后端服务器将连接到 APN 并通过提供相同的设备令牌来指示哪个设备应该接收通知来发送推送通知。
Note that the device token may change in the future due to various reasons, so use NSUserDefaults, a local key-value store, to persist the token locally and only update your backend when the token has changed, to avoid unnecessary requests.
请注意,设备令牌将来可能会因各种原因发生变化,因此请使用本地键值存储 NSUserDefaults 将令牌保存在本地,并且仅在令牌发生变化时才更新您的后端,以避免不必要的请求。
Run your app on a physical iOS device (the iOS simulator cannot receive notifications) after making the necessary modifications to AppDelegate.swift. Look for the following dialog, and press OK to permit your app to receive push notifications:
在对 AppDelegate.swift 进行必要的修改后,在物理 iOS 设备上运行您的应用程序(iOS 模拟器无法接收通知)。查找以下对话框,然后按 OK 以允许您的应用接收推送通知:
Alert Dialog
警报对话框
Within a second or two, the Xcode console should display your device's unique token. Copy it and save it for later.
在一两秒钟内,Xcode 控制台应该会显示您设备的唯一令牌。复制并保存以备后用。
Prepare to Receive Notifications
准备接收通知
Add the following callback in AppDelegate.swift which will be invoked when your app receives a push notification sent by your backend server:
在 AppDelegate.swift 中添加以下回调,当您的应用收到后端服务器发送的推送通知时将调用该回调:
##代码##Note that this callback will only be invoked whenever the user has either clicked or swiped to interact with your push notification from the lock screen / Notification Center, or if your app was open when the push notification was received by the device.
请注意,仅当用户在锁定屏幕/通知中心点击或滑动与您的推送通知进行交互时,或者当设备收到推送通知时您的应用程序处于打开状态时,才会调用此回调。
It's up to you to develop the actual logic that gets executed when a notification is interacted with. For example, if you have a messenger app, a "new message" push notification should open the relevant chat page and cause the list of messages to be updated from the server. Make use of the data object which will contain any data that you send from your application backend, such as the chat ID, in the messenger app example.
开发与通知交互时执行的实际逻辑取决于您。例如,如果您有一个信使应用程序,“新消息”推送通知应该打开相关的聊天页面并导致从服务器更新消息列表。在信使应用程序示例中,使用数据对象,该对象将包含您从应用程序后端发送的任何数据,例如聊天 ID。
It's important to note that in the event your app is open when a push notification is received, the user will not see the notification at all, and it is up to you to notify the user in some way. This StackOverflow question lists some possible workarounds, such as displaying an in-app banner similar to the stock iOS notification banner.
需要注意的是,如果您的应用程序在收到推送通知时处于打开状态,用户将根本看不到该通知,您需要以某种方式通知用户。此 StackOverflow 问题列出了一些可能的解决方法,例如显示类似于股票 iOS 通知横幅的应用内横幅。
Generate an APNs Auth Key
生成 APNs 身份验证密钥
Open the APNs Auth Key page in your Developer Center and click the + button to create a new APNs Auth Key.
在开发人员中心打开 APNs Auth Key 页面,然后单击 + 按钮创建新的APNs Auth Key。
In the next page, select Apple Push Notification Authentication Key (Sandbox & Production) and click Continue at the bottom of the page.
在下一页中,选择 Apple Push Notification Authentication Key (Sandbox & Production) 并单击页面底部的 Continue。
Apple will then generate a .p8
key file containing your APNs Auth Key.
然后 Apple 将生成一个.p8
包含您的 APNs Auth Key的密钥文件。
Download the .p8
key file to your computer and save it for later. Also, be sure to write down the Key ID somewhere, as you'll need it later when connecting to APNs.
将.p8
密钥文件下载到您的计算机并保存以备后用。另外,请务必在某处写下密钥 ID,因为稍后连接到 APN 时您将需要它。
Send Push Notifications
发送推送通知
Now, look at here to understand, APNS flow: How do iOS Push Notifications work?
现在,看这里就明白了,APNS 流程:iOS 推送通知如何工作?