类型不符合协议NSObjectProtocol

时间:2017-06-07 17:24:04

标签: ios swift swift3 apple-push-notifications

这是我的Notification方法,可以从几个地方调用,但这就是我想要做的事情:

import Foundation
import UserNotifications

class NotificationUtil {

    @available(iOS 10.0, *)
    static func requestNotification(title: String, body: String, interval: TimeInterval, identifier: String, delegate: UNUserNotificationCenterDelegate) {

        let content = UNMutableNotificationContent()
        content.title = title
        content.body = body
        content.sound = UNNotificationSound.default()

        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: interval, repeats: false)
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

        UNUserNotificationCenter.current().delegate = delegate
        UNUserNotificationCenter.current().add(request){(error) in

            if (error != nil){
                print(error?.localizedDescription)
            }
        }
    }
}

extension NotificationUtil: UNUserNotificationCenterDelegate {
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        print("Tapped in notification")
    }


    //This is key callback to present notification while the app is in foreground
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        print("Notification being triggered")
        //You can either present alert ,sound or increase badge while the app is in foreground too with ios 10
        //to distinguish between notifications
        if notification.request.identifier == "requestIdentifier" {

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

        }
    }

}

在扩展热线上,我得到Type 'Notification Util' does not conform to protocol 'NSObjectProtocol'.因此我将NSObject添加到类NotificationUtil中,如下所示:

class NotificationUtil: NSObject

然后在ViewController中,我调用以下方式:

//local notification
                    if #available(iOS 10.0, *) {
                        NotificationUtil.requestNotification(title: "title",
                                                             body: "body",
                                                             interval: 1.0,
                                                             identifier: "requestIdentifier",
                                                             delegate: NotificationUtil)
                    } else {
                        // Fallback on earlier versions
                    }

然后不会调用通知。我在这里缺少什么?

另一方面,如果我将扩展添加到ViewController,它就可以了。

0 个答案:

没有答案