ios - Swift iOS 10 的推送通知

标签 ios swift push-notification notifications ios10

我正在努力让推送通知与 Swift 和 iOS 10 一起使用。注册似乎成功完成,但创建通知在设备上没有任何作用并返回 nil 错误。有什么想法我想念的吗?

import Foundation
import UIKit
import UserNotifications
class SPKPushNotifications
{
    class func register(application:UIApplication){
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
                // Enable or disable features based on authorization.
                application.registerForRemoteNotifications()
            }
        } else {
            let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound]
            let pushNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil)
            application.registerUserNotificationSettings(pushNotificationSettings)
            application.registerForRemoteNotifications()
        }
    }
    class func unregister(application:UIApplication){
        application.unregisterForRemoteNotifications()
    }
    class func create(title:String, body:String, delay:Double, repeats:Bool){
        if #available(iOS 10.0, *) {
            let content = UNMutableNotificationContent()
            content.title = title
            content.body = body
            content.sound = UNNotificationSound.default() //idk if we're gonna want something else
            content.badge = NSNumber(value:UIApplication.shared.applicationIconBadgeNumber+1)
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval:delay, repeats:repeats)
            let request = UNNotificationRequest(identifier:title, content:content, trigger:trigger)
            let center = UNUserNotificationCenter.current()
            center.add(request){ (error) in
                print(error)
            }

        } else {
            // Fallback on earlier versions
        }
    }
    class func delete(){
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.removeAllDeliveredNotifications()
        } else {
            // Fallback on earlier versions
        }
    }
}

最佳答案

如果应用程序在前台,您将看不到通知。尝试在应用程序处于后台时将请求添加到通知中心。

您可以(仅针对此测试)通过添加几秒钟的 sleep 并将您的应用程序移至后台来做到这一点。或者将通知安排到应用程序未在前台运行时的稍后时间。

关于ios - Swift iOS 10 的推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40266228/

相关文章:

ios - UIScrollView 将内容推离页面

swift - 继承自@objc协议(protocol)

android - 有多少用户启用了推送通知?

java - 在小米设备的锁定屏幕上显示通知

iphone - 使用 HTTP Post 方法如何在 iphone 中制作登录页面

ios - 添加 NSManagedObject 子类时出现重复符号错误,链接重复

ios - 调用另一个 View Controller 的 func 来控制 alpha 返回 nil 错误

ios - 快速更改 UImenu 的位置

ios - cordova-plugins-qrscanner 无法为 ios 构建

android - 使用XMPP在android中用户离线时向用户发送通知