I am trying to setup a push notification system for my application. I have a server and a developer license to setup the push notification service.
我正在为我的应用程序安装一个推送通知系统。我有一个服务器和一个开发人员许可证来设置推送通知服务。
I am currently running my app in Swift. I would like to be able to send the notifications remotely from my server. How can I do this?
我现在正在用Swift运行我的应用。我希望能够从我的服务器远程发送通知。我该怎么做呢?
10 个解决方案
#1
30
While the answer is given well to handle push notification, still I believe to share integrated complete case at once to ease:
虽然给出的答案很好地处理了推送通知,但我仍然相信要立即共享集成的完整案例,以方便:
To Register Application for APNS, (Include the following code in didFinishLaunchingWithOptions method inside AppDelegate.swift)
要为APNS注册应用程序,(在AppDelegate.swift内的didFinishLaunchingWithOptions方法中包含以下代码)
IOS 9
IOS 9
var settings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes:UIUserNotificationType.Alert|UIUserNotificationType.Sound, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
After IOS 10
在IOS 10
Introduced UserNotifications framework:
介绍了UserNotifications框架:
Import the UserNotifications framework and add the UNUserNotificationCenterDelegate in AppDelegate.swift
导入UserNotifications框架,并在AppDelegate.swift中添加UNUserNotificationCenterDelegate
To Register Application for APNS
注册APNS的申请。
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
application.registerForRemoteNotifications()
This will call following delegate method
这将调用下面的委托方法
func application(application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
//send this device token to server
}
//Called if unable to register for APNS.
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println(error)
}
On Receiving notification following delegate will call:
在收到通知后,下列代表将调用:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
println("Recived: \(userInfo)")
//Parsing userinfo:
var temp : NSDictionary = userInfo
if let info = userInfo["aps"] as? Dictionary<String, AnyObject>
{
var alertMsg = info["alert"] as! String
var alert: UIAlertView!
alert = UIAlertView(title: "", message: alertMsg, delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
To be identify the permission given we can use:
确定我们可使用的许可:
UNUserNotificationCenter.current().getNotificationSettings(){ (setttings) in
switch setttings.soundSetting{
case .enabled:
print("enabled sound")
case .disabled:
print("not allowed notifications")
case .notSupported:
print("something went wrong here")
}
}
So the checklist of APNS:
APNS的清单是
- Create AppId allowed with Push Notification
- 创建允许使用Push通知的AppId
- Create SSL certificate with valid certificate and app id
- 创建具有有效证书和应用程序id的SSL证书
- Create Provisioning profile with same certificate and make sure to add device in case of sandboxing(development provisioning) Note: That will be good if Create Provisioning profile after SSL Certificate.
- 创建具有相同证书的配置文件,并确保在出现沙箱(开发配置文件)时添加设备。
With Code:
与代码:
- Register app for push notification
- 为推送通知注册app
- Handle didRegisterForRemoteNotificationsWithDeviceToken method
- 处理didRegisterForRemoteNotificationsWithDeviceToken方法
- Set targets> Capability> background modes> Remote Notification
- 设置目标>功能>后台模式>远程通知
- Handle didReceiveRemoteNotification
- 处理didReceiveRemoteNotification
#2
74
Swift 2:
斯威夫特2:
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
#3
34
To register to receive push notifications via Apple Push Service you have to call a registerForRemoteNotifications()
method of UIApplication
.
要通过Apple push服务注册以接收推送通知,您必须调用UIApplication的registerforremotenotiations()方法。
If registration succeeds, the app calls your app delegate object’s application:didRegisterForRemoteNotificationsWithDeviceToken:
method and passes it a device token.
如果注册成功,应用程序将调用您的应用程序委托对象的应用程序:didRegisterForRemoteNotificationsWithDeviceToken:方法并将设备令牌传递给它。
You should pass this token along to the server you use to generate push notifications for the device. If registration fails, the app calls its app delegate’s application:didFailToRegisterForRemoteNotificationsWithError:
method instead.
您应该将此令牌传递给用于为设备生成推送通知的服务器。如果注册失败,应用程序调用其应用程序委托的应用程序:didFailToRegisterForRemoteNotificationsWithError: method。
Have a look into Local and Push Notification Programming Guide.
查看本地和推送通知编程指南。
#4
25
registerForRemoteNotification()
has been removed from ios8.
从ios8中删除了registerForRemoteNotification()。
So you should use UIUserNotification
你应该使用UIUserNotification
CODE EXAMPLE:
代码示例:
var type = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound;
var setting = UIUserNotificationSettings(forTypes: type, categories: nil);
UIApplication.sharedApplication().registerUserNotificationSettings(setting);
UIApplication.sharedApplication().registerForRemoteNotifications();
Hope this will help you.
希望这能对你有所帮助。
#5
15
To support ios 8 and before, use this:
要支持ios 8和以前的版本,请使用以下命令:
// Register for Push Notitications, if running iOS 8
if application.respondsToSelector("registerUserNotificationSettings:") {
let types:UIUserNotificationType = (.Alert | .Badge | .Sound)
let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
// Register for Push Notifications before iOS 8
application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound)
}
#6
8
Thanks for the earlier answers. Xcode has made some changes and here's the SWIFT 2 code that passes XCode 7 code check and supports both iOS 7 and above:
谢谢你之前的回答。Xcode做了一些修改,以下是通过Xcode 7代码检查并同时支持iOS 7及以上版本的SWIFT 2代码:
if #available(iOS 8.0, *) {
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
} else {
let settings = UIRemoteNotificationType.Alert.union(UIRemoteNotificationType.Badge).union(UIRemoteNotificationType.Sound)
UIApplication.sharedApplication().registerForRemoteNotificationTypes(settings)
}
#7
7
Swift 4
I think this is the correct way for setup in iOS 8
and above.
我认为这是ios8及以上版本安装的正确方式。
Turn on Push Notifications
in the Capabilities
tab
打开功能选项卡中的推送通知。
Import UserNotifications
进口UserNotifications
import UserNotifications
Modify didFinishLaunchingWithOptions
修改didFinishLaunchingWithOptions
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {
// If your app wasn’t running and the user launches it by tapping the push notification, the push notification is passed to your app in the launchOptions
let aps = notification["aps"] as! [String: AnyObject]
UIApplication.shared.applicationIconBadgeNumber = 0
}
registerForPushNotifications()
return true
}
It’s extremely important to call
registerUserNotificationSettings(_:)
every time the app launches. This is because the user can, at any time, go into the Settings app and change the notification permissions.application(_:didRegisterUserNotificationSettings:)
will always provide you with what permissions the user currently has allowed for your app.每次应用程序启动时,给registerUserNotificationSettings(_:)打电话是非常重要的。这是因为用户可以在任何时候进入设置应用程序并更改通知权限。应用程序(_:didRegisterUserNotificationSettings:)将始终为您提供用户当前允许的应用程序权限。
Copy paste this AppDelegate
extension
复制粘贴这个AppDelegate扩展名
// Push Notificaion
extension AppDelegate {
func registerForPushNotifications() {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
[weak self] (granted, error) in
print("Permission granted: \(granted)")
guard granted else {
print("Please enable \"Notifications\" from App Settings.")
self?.showPermissionAlert()
return
}
self?.getNotificationSettings()
}
} else {
let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
}
}
@available(iOS 10.0, *)
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
print("Device Token: \(token)")
//UserDefaults.standard.set(token, forKey: DEVICE_TOKEN)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If your app was running and in the foreground
// Or
// If your app was running or suspended in the background and the user brings it to the foreground by tapping the push notification
print("didReceiveRemoteNotification /(userInfo)")
guard let dict = userInfo["aps"] as? [String: Any], let msg = dict ["alert"] as? String else {
print("Notification Parsing Error")
return
}
}
func showPermissionAlert() {
let alert = UIAlertController(title: "WARNING", message: "Please enable access to Notifications in the Settings app.", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) {[weak self] (alertAction) in
self?.gotoAppSettings()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(settingsAction)
alert.addAction(cancelAction)
DispatchQueue.main.async {
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
}
}
private func gotoAppSettings() {
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.openURL(settingsUrl)
}
}
}
Check out: Push Notifications Tutorial: Getting Started
查看:推送通知教程:开始
#8
1
Swift 3:
斯威夫特3:
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
UIApplication.shared.registerForRemoteNotifications()
Make sure to import UserNotifications at the top of your view controller.
确保在视图控制器的顶部导入用户通知。
import UserNotifications
#9
0
You can send notification using the following code snippet:
您可以使用以下代码片段发送通知:
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
if(UIApplication.sharedApplication().currentUserNotificationSettings() == settings ){
//OK
}else{
//KO
}
#10
0
I use this code snip in AppDelegate.swift:
我在appdelegate中使用这个代码剪切。
let pushType = UIUserNotificationType.alert.union(.badge).union(.sound)
let pushSettings = UIUserNotificationSettings(types: pushType
, categories: nil)
application.registerUserNotificationSettings(pushSettings)
application.registerForRemoteNotifications()
#1
30
While the answer is given well to handle push notification, still I believe to share integrated complete case at once to ease:
虽然给出的答案很好地处理了推送通知,但我仍然相信要立即共享集成的完整案例,以方便:
To Register Application for APNS, (Include the following code in didFinishLaunchingWithOptions method inside AppDelegate.swift)
要为APNS注册应用程序,(在AppDelegate.swift内的didFinishLaunchingWithOptions方法中包含以下代码)
IOS 9
IOS 9
var settings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes:UIUserNotificationType.Alert|UIUserNotificationType.Sound, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
After IOS 10
在IOS 10
Introduced UserNotifications framework:
介绍了UserNotifications框架:
Import the UserNotifications framework and add the UNUserNotificationCenterDelegate in AppDelegate.swift
导入UserNotifications框架,并在AppDelegate.swift中添加UNUserNotificationCenterDelegate
To Register Application for APNS
注册APNS的申请。
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
application.registerForRemoteNotifications()
This will call following delegate method
这将调用下面的委托方法
func application(application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
//send this device token to server
}
//Called if unable to register for APNS.
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println(error)
}
On Receiving notification following delegate will call:
在收到通知后,下列代表将调用:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
println("Recived: \(userInfo)")
//Parsing userinfo:
var temp : NSDictionary = userInfo
if let info = userInfo["aps"] as? Dictionary<String, AnyObject>
{
var alertMsg = info["alert"] as! String
var alert: UIAlertView!
alert = UIAlertView(title: "", message: alertMsg, delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
To be identify the permission given we can use:
确定我们可使用的许可:
UNUserNotificationCenter.current().getNotificationSettings(){ (setttings) in
switch setttings.soundSetting{
case .enabled:
print("enabled sound")
case .disabled:
print("not allowed notifications")
case .notSupported:
print("something went wrong here")
}
}
So the checklist of APNS:
APNS的清单是
- Create AppId allowed with Push Notification
- 创建允许使用Push通知的AppId
- Create SSL certificate with valid certificate and app id
- 创建具有有效证书和应用程序id的SSL证书
- Create Provisioning profile with same certificate and make sure to add device in case of sandboxing(development provisioning) Note: That will be good if Create Provisioning profile after SSL Certificate.
- 创建具有相同证书的配置文件,并确保在出现沙箱(开发配置文件)时添加设备。
With Code:
与代码:
- Register app for push notification
- 为推送通知注册app
- Handle didRegisterForRemoteNotificationsWithDeviceToken method
- 处理didRegisterForRemoteNotificationsWithDeviceToken方法
- Set targets> Capability> background modes> Remote Notification
- 设置目标>功能>后台模式>远程通知
- Handle didReceiveRemoteNotification
- 处理didReceiveRemoteNotification
#2
74
Swift 2:
斯威夫特2:
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
#3
34
To register to receive push notifications via Apple Push Service you have to call a registerForRemoteNotifications()
method of UIApplication
.
要通过Apple push服务注册以接收推送通知,您必须调用UIApplication的registerforremotenotiations()方法。
If registration succeeds, the app calls your app delegate object’s application:didRegisterForRemoteNotificationsWithDeviceToken:
method and passes it a device token.
如果注册成功,应用程序将调用您的应用程序委托对象的应用程序:didRegisterForRemoteNotificationsWithDeviceToken:方法并将设备令牌传递给它。
You should pass this token along to the server you use to generate push notifications for the device. If registration fails, the app calls its app delegate’s application:didFailToRegisterForRemoteNotificationsWithError:
method instead.
您应该将此令牌传递给用于为设备生成推送通知的服务器。如果注册失败,应用程序调用其应用程序委托的应用程序:didFailToRegisterForRemoteNotificationsWithError: method。
Have a look into Local and Push Notification Programming Guide.
查看本地和推送通知编程指南。
#4
25
registerForRemoteNotification()
has been removed from ios8.
从ios8中删除了registerForRemoteNotification()。
So you should use UIUserNotification
你应该使用UIUserNotification
CODE EXAMPLE:
代码示例:
var type = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound;
var setting = UIUserNotificationSettings(forTypes: type, categories: nil);
UIApplication.sharedApplication().registerUserNotificationSettings(setting);
UIApplication.sharedApplication().registerForRemoteNotifications();
Hope this will help you.
希望这能对你有所帮助。
#5
15
To support ios 8 and before, use this:
要支持ios 8和以前的版本,请使用以下命令:
// Register for Push Notitications, if running iOS 8
if application.respondsToSelector("registerUserNotificationSettings:") {
let types:UIUserNotificationType = (.Alert | .Badge | .Sound)
let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
// Register for Push Notifications before iOS 8
application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound)
}
#6
8
Thanks for the earlier answers. Xcode has made some changes and here's the SWIFT 2 code that passes XCode 7 code check and supports both iOS 7 and above:
谢谢你之前的回答。Xcode做了一些修改,以下是通过Xcode 7代码检查并同时支持iOS 7及以上版本的SWIFT 2代码:
if #available(iOS 8.0, *) {
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
} else {
let settings = UIRemoteNotificationType.Alert.union(UIRemoteNotificationType.Badge).union(UIRemoteNotificationType.Sound)
UIApplication.sharedApplication().registerForRemoteNotificationTypes(settings)
}
#7
7
Swift 4
I think this is the correct way for setup in iOS 8
and above.
我认为这是ios8及以上版本安装的正确方式。
Turn on Push Notifications
in the Capabilities
tab
打开功能选项卡中的推送通知。
Import UserNotifications
进口UserNotifications
import UserNotifications
Modify didFinishLaunchingWithOptions
修改didFinishLaunchingWithOptions
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {
// If your app wasn’t running and the user launches it by tapping the push notification, the push notification is passed to your app in the launchOptions
let aps = notification["aps"] as! [String: AnyObject]
UIApplication.shared.applicationIconBadgeNumber = 0
}
registerForPushNotifications()
return true
}
It’s extremely important to call
registerUserNotificationSettings(_:)
every time the app launches. This is because the user can, at any time, go into the Settings app and change the notification permissions.application(_:didRegisterUserNotificationSettings:)
will always provide you with what permissions the user currently has allowed for your app.每次应用程序启动时,给registerUserNotificationSettings(_:)打电话是非常重要的。这是因为用户可以在任何时候进入设置应用程序并更改通知权限。应用程序(_:didRegisterUserNotificationSettings:)将始终为您提供用户当前允许的应用程序权限。
Copy paste this AppDelegate
extension
复制粘贴这个AppDelegate扩展名
// Push Notificaion
extension AppDelegate {
func registerForPushNotifications() {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
[weak self] (granted, error) in
print("Permission granted: \(granted)")
guard granted else {
print("Please enable \"Notifications\" from App Settings.")
self?.showPermissionAlert()
return
}
self?.getNotificationSettings()
}
} else {
let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
}
}
@available(iOS 10.0, *)
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
print("Device Token: \(token)")
//UserDefaults.standard.set(token, forKey: DEVICE_TOKEN)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If your app was running and in the foreground
// Or
// If your app was running or suspended in the background and the user brings it to the foreground by tapping the push notification
print("didReceiveRemoteNotification /(userInfo)")
guard let dict = userInfo["aps"] as? [String: Any], let msg = dict ["alert"] as? String else {
print("Notification Parsing Error")
return
}
}
func showPermissionAlert() {
let alert = UIAlertController(title: "WARNING", message: "Please enable access to Notifications in the Settings app.", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) {[weak self] (alertAction) in
self?.gotoAppSettings()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(settingsAction)
alert.addAction(cancelAction)
DispatchQueue.main.async {
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
}
}
private func gotoAppSettings() {
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.openURL(settingsUrl)
}
}
}
Check out: Push Notifications Tutorial: Getting Started
查看:推送通知教程:开始
#8
1
Swift 3:
斯威夫特3:
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
UIApplication.shared.registerForRemoteNotifications()
Make sure to import UserNotifications at the top of your view controller.
确保在视图控制器的顶部导入用户通知。
import UserNotifications
#9
0
You can send notification using the following code snippet:
您可以使用以下代码片段发送通知:
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
if(UIApplication.sharedApplication().currentUserNotificationSettings() == settings ){
//OK
}else{
//KO
}
#10
0
I use this code snip in AppDelegate.swift:
我在appdelegate中使用这个代码剪切。
let pushType = UIUserNotificationType.alert.union(.badge).union(.sound)
let pushSettings = UIUserNotificationSettings(types: pushType
, categories: nil)
application.registerUserNotificationSettings(pushSettings)
application.registerForRemoteNotifications()