从函数返回self以符合协议UNUserNotificationCenterDelegate

时间:2017-01-14 14:25:55

标签: ios swift unusernotificationcenter

我一直坚持开发新的应用程序。我希望,有人可以帮助我,解决问题。我很高兴;)

目前我正在尝试显示通知对象的警报,该警报由UNUserNotifictionCenter触发。当您离开应用程序并触发触发器时,警报会显示,但是一旦您在应用程序中工作并且应该触发警报,就不会发生任何事情。为此,您必须采用UNUserNotificationCenterDelegate,它可以显示通知对象的警报。我被卡住了。

UNUserNotificationCenterDelegate继承NSObjectProtocol,需要一个名为'self'()的函数,该函数的实现也返回一个值,该值应为self类型

要回复此请求的自我,我尝试了两个选项:

func `self`() -> Self {
    var delegate = type(of: self)
    //delegate = type(of: self).self
    return delegate
}

另一种选择,使用线程样式:

func `self`() -> Self {
    var delegate = NSObject().value(forKey: Thread().name!) as! Self
    return delegate
}

这两个选项都无法工作。所以如果有人能帮助我,我会非常感激。

问候Javed

2 个答案:

答案 0 :(得分:2)

我认为你最好继承你想成为UNUserNotificationCenterDelegate NSObject的班级

class MyUserNotificationCenterDelegate : NSObject, UNUserNotificationCenterDelegate {

     // implementation
}

众所周知NSObject实现了NSObjectProtocol

希望它有所帮助!

答案 1 :(得分:1)

您的AppDelegate应符合协议UNUserNotificationCenterDelegate,以便在应用处于前台时显示通知。

只需将以下内容添加到AppDelegate定义中:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

现在,您需要在AppDelegate中添加以下函数,以确认此协议

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        completionHandler([.sound,.alert,.badge])
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    //do whatever you want to here
    completionHandler()
}

希望这会有所帮助。 :)

相关问题