ios 如何在 Swift 中设置推送通知
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24899257/
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 to set up push notifications in Swift
提问by BlakeH
I am trying to set up a push notification system for my application. I have a server and a developer license to set up 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 中运行我的应用程序。我希望能够从我的服务器远程发送通知。我怎样才能做到这一点?
采纳答案by Arvind
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
// If granted comes true you can enabled features based on authorization.
guard granted else { return }
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
- Create SSL certificate with valid certificate and app id
- Create Provisioning profile with same certificate and make sure to add device in case of sandboxing(development provisioning)
- 使用推送通知创建允许的 AppId
- 使用有效的证书和应用程序 ID 创建 SSL 证书
- 创建具有相同证书的配置文件,并确保在沙盒(开发配置)的情况下添加设备
Note:That will be good if Create Provisioning profile after SSL Certificate.
注意:如果在 SSL 证书之后创建配置文件,那会很好。
With Code:
使用代码:
- Register app for push notification
- Handle didRegisterForRemoteNotificationsWithDeviceToken method
- Set targets> Capability> background modes> Remote Notification
- Handle didReceiveRemoteNotification
- 注册应用以获得推送通知
- 处理 didRegisterForRemoteNotificationsWithDeviceToken 方法
- 设置目标>能力>后台模式>远程通知
- 处理 didReceiveRemoteNotification
回答by Adam Waite
Swift 2:
斯威夫特 2:
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
回答by RaffAl
To register to receive push notifications via Apple Push Service you have to call a registerForRemoteNotifications()
method of UIApplication
.
要注册以通过 Apple 推送服务接收推送通知,您必须调用 的registerForRemoteNotifications()
方法UIApplication
。
If registration succeeds, the app calls your app delegate object's application:didRegisterForRemoteNotificationsWithDeviceToken:
method and passes it a device token.
如果注册成功,应用程序将调用您的应用程序委托对象的application: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.
您应该将此令牌传递给用于为设备生成推送通知的服务器。如果注册失败,应用程序会调用其应用程序委托的application:didFailToRegisterForRemoteNotificationsWithError:
方法。
Have a look into Local and Push Notification Programming Guide.
查看本地和推送通知编程指南。
回答by Dog Su
registerForRemoteNotification()
has been removed from ios8.
registerForRemoteNotification()
已从 ios8 中删除。
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.
希望这会帮助你。
回答by Gmeister4
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)
}
回答by Warif Akhand Rishi
Swift 4
斯威夫特 4
I think this is the correct way for setup in iOS 8
and above.
我认为这是在设置正确的方法iOS 8
和上面。
Turn on Push Notifications
in the Capabilities
tab
Push Notifications
在Capabilities
选项卡中
打开
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(_:)
每次应用启动时调用都非常重要。这是因为用户可以随时进入“设置”应用程序并更改通知权限。application(_: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
查看:推送通知教程:入门
回答by Oliver Zhang
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)
}
回答by jojo
Swift 4
斯威夫特 4
Import the UserNotifications framework and add the UNUserNotificationCenterDelegate in AppDelegate
导入 UserNotifications 框架并在 AppDelegate 中添加 UNUserNotificationCenterDelegate
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate
To Register Application for APNS, (Include the following code in didFinishLaunchingWithOptions method inside AppDelegate.swift)
为 APNS 注册应用程序,(在 AppDelegate.swift 中的 didFinishLaunchingWithOptions 方法中包含以下代码)
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: Data) {
//send this device token to server
}
//Called if unable to register for APNS.
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print(error)
}
On Receiving notification following delegate will call:
收到通知后,以下代表将调用:
private func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print("Recived: \(userInfo)")
//Parsing userinfo:
}
回答by Henry
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 UserNotificationsat the top of your view controller.
确保在视图控制器的顶部导入UserNotifications。
import UserNotifications
回答by ZYiOS
I use this code snip in AppDelegate.swift:
我在 AppDelegate.swift 中使用此代码片段:
let pushType = UIUserNotificationType.alert.union(.badge).union(.sound)
let pushSettings = UIUserNotificationSettings(types: pushType
, categories: nil)
application.registerUserNotificationSettings(pushSettings)
application.registerForRemoteNotifications()