如何在Swift中设置推送通知

我正在尝试为我的应用程序设置一个推送通知系统。 我有一个服务器和开发者许可证来设置推送通知服务。

我目前在Swift中运行我的应用程序。 我希望能够从我的服务器远程发送通知。 我该怎么做?

要通过Apple Push Service注册接收推送通知,您必须调用UIApplicationregisterForRemoteNotifications()方法。

如果注册成功,应用程序将调用您的应用程序委托对象的application:didRegisterForRemoteNotificationsWithDeviceToken:方法并将其传递给设备令牌。

您应该将此令牌传递给您用于为设备生成推送通知的服务器。 如果注册失败,应用程序将调用其应用程序委托的application:didFailToRegisterForRemoteNotificationsWithError:方法。

查看本地和推送通知编程指南 。

Swift 2:

 let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) UIApplication.sharedApplication().registerForRemoteNotifications() 

虽然处理推送通知的答案很好,但我仍然相信马上分享整合的完整案例来缓解:

为APNS注册应用程序(在AppDelegate.swift中的didFinishLaunchingWithOptions方法中包含以下代码)

 var settings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes:UIUserNotificationType.Alert|UIUserNotificationType.Sound, categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) UIApplication.sharedApplication().registerForRemoteNotifications() 

这将调用下面的委托方法

 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) } 

在接到通知后,代表将会打电话给:

 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() } } 

所以APNS的清单:

  1. 创build允许推送通知的AppId
  2. 使用有效的证书和应用程序ID创buildSSL证书
  3. 使用相同的证书创buildconfigurationconfiguration文件,并确保在沙箱(开发configuration)情况下添加设备注意:如果在SSL证书之后创buildconfigurationconfiguration文件,那将会很好。

使用代码:

  1. 注册应用程序推送通知
  2. 处理didRegisterForRemoteNotificationsWithDeviceToken方法
  3. 设置目标>能力>背景模式>远程通知
  4. 处理didReceiveRemoteNotification

registerForRemoteNotification()已经从ios8中删除。

所以你应该使用UIUserNotification

代码示例:

 var type = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound; var setting = UIUserNotificationSettings(forTypes: type, categories: nil); UIApplication.sharedApplication().registerUserNotificationSettings(setting); UIApplication.sharedApplication().registerForRemoteNotifications(); 

希望这会帮助你。

为了支持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) } 

感谢以前的答案。 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) } 

我认为这是iOS 8及以上iOS 8设置正确方法

 func registerForPushNotifications(application: UIApplication) { let notificationSettings = UIUserNotificationSettings(forTypes: [.Badge, .Sound, .Alert], categories: nil) application.registerUserNotificationSettings(notificationSettings) } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { registerForPushNotifications(application) if let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject] { let aps = notification["aps"] 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 } } 

每次启动应用程序时调用registerUserNotificationSettings(_:)是非常重要的。 这是因为用户可以随时进入“设置”应用程序并更改通知权限。 application(_:didRegisterUserNotificationSettings:)将始终为您提供用户当前允许的应用程序权限。

 func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) { if notificationSettings.types != .None { application.registerForRemoteNotifications() } } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let tokenChars = UnsafePointer<CChar>(deviceToken.bytes) var tokenString = "" for i in 0..<deviceToken.length { tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]]) } print("Device Token:", tokenString) } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { print("Failed to register:", error) } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { let aps = userInfo["aps"] as! [String: AnyObject] // 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 } 

查看: 推送通知教程:入门

Swift 3:

 let center = UNUserNotificationCenter.current() center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in // Enable or disable features based on authorization. } UIApplication.shared.registerForRemoteNotifications() 

确保在视图控制器的顶部导入UserNotifications

 import UserNotifications 

您可以使用以下代码片段发送通知:

 let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) if(UIApplication.sharedApplication().currentUserNotificationSettings() == settings ){ //OK }else{ //KO }