UNUserNotificationCenter确实收到带有完成处理程序的响应,从不称为iOS10,swift 2.3

时间:2016-08-15 11:48:25

标签: xcode notifications ios10

我正在iOS10中安排新通知,如下所示:

func scheduleNotification (event : Meeting, todaysBadgeCounter: Int) {

    if #available(iOS 10.0, *) {

        let minutesBefore = 10
        //interval in seconds from current point in time to notification
        let interval : NSTimeInterval = NSTimeInterval(secondsFromNowTo(event.startTime.dateByAddingTimeInterval(-minutesBefore * 60)))

        //only schedule in the future
        if(interval > 0){


            let category = NotificationsController.notificationCategory

            let center = NotificationsController.notificationCenter
            center.setNotificationCategories([category])
            let content = UNMutableNotificationContent()

            content.title = NSString.localizedUserNotificationStringForKey(event.title, arguments: nil)
            if(minutesBefore <= 1){
                content.body = NSString.localizedUserNotificationStringForKey("IOS10: Your \(event.title) is about to start", arguments: nil)
            }else{
                content.body = NSString.localizedUserNotificationStringForKey("IOS10: You have \(event.title) in \(Int(minutesBefore)) minutes", arguments: nil)

            }
            content.sound = UNNotificationSound.defaultSound()

            let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: interval, repeats: false)
            let identifier = NSString.localizedUserNotificationStringForKey("sampleRequest\(event.UUID)", arguments: nil)
            let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger)

            //setting the delegate
            center.delegate = self

            center.addNotificationRequest(request, withCompletionHandler: { (error) in
                // handle the error if needed
                log.error(error?.localizedDescription)
                print("SCHEDULING >=iOS10:", event.title, ", interval:", interval)
            })
        }


//return category
@available(iOS 10.0, *)
class var notificationCategory : UNNotificationCategory {
    struct Static {
        static let callNow = UNNotificationAction(identifier: NotificationActions.callNow.rawValue, title: "Call now", options: [])
        static let clear = UNNotificationAction(identifier: NotificationActions.clear.rawValue, title: "Clear", options: [])
        static let category : UNNotificationCategory = UNNotificationCategory.init(identifier: "CALLINNOTIFICATION", actions: [callNow, clear], intentIdentifiers: [], options: [])

    }
    return Static.category
}

我可以安排通知,并在合适的时间接收本地通知。 BUT:我根据本教程使用的委托方法永远不会执行,但每次点击通知时都会执行didReceiveLocalNotification:

extension NotificationsController: UNUserNotificationCenterDelegate {

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

    print("IOS10 delivered")

    // Response has actionIdentifier, userText, Notification (which has Request, which has Trigger and Content)
    switch response.actionIdentifier {
    case NotificationActions.NotifyBefore.rawValue:
        print("notify")
        break

    case NotificationActions.callNow.rawValue:
        print("callNow")
        break
    case NotificationActions.clear.rawValue:
        print("clear")
    default: break
    }
}

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {

        // Delivers a notification to an app running in the foreground.
        print("IOS10 delivered 2222")

    }
}

是不是不推荐使用didReceiveLocalNotification?如何调用这些方法?

更新

我用这里的一些建议更新了我的代码,即:

  1. 我添加了将UNUserNotificationCenter.delegate分配给applicationDidFinishLaunchingWithOptions。
  2. 我还尝试将这些方法(委托方法)从扩展中移出到NotificationsController.swift类,并将此类设置为UNUserNotificationCenterDelegate。对我来说也没用。

10 个答案:

答案 0 :(得分:16)

请求标识符不是通知类别。

只需添加以下行:

content.categoryIdentifier = identifier

更新: 刚刚制作了一个简单的应用一切似乎都很好:

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UNUserNotificationCenter.current().delegate = self

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if granted {
            self.registerCategory()
            self.scheduleNotification(event: "test", interval: 3)
            self.scheduleNotification(event: "test2", interval: 5)
        }
    }

    return true
}

func registerCategory() -> Void{

    let callNow = UNNotificationAction(identifier: "call", title: "Call now", options: [])
    let clear = UNNotificationAction(identifier: "clear", title: "Clear", options: [])
    let category : UNNotificationCategory = UNNotificationCategory.init(identifier: "CALLINNOTIFICATION", actions: [callNow, clear], intentIdentifiers: [], options: [])

    let center = UNUserNotificationCenter.current()
    center.setNotificationCategories([category])

}

func scheduleNotification (event : String, interval: TimeInterval) {
    let content = UNMutableNotificationContent()

    content.title = event
    content.body = "body"
    content.categoryIdentifier = "CALLINNOTIFICATION"
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: interval, repeats: false)
    let identifier = "id_"+event
    let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger)

    let center = UNUserNotificationCenter.current()
        center.add(request, withCompletionHandler: { (error) in
    })

}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("didReceive")
    completionHandler()
}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print("willPresent")
    completionHandler([.badge, .alert, .sound])
}

}

更新2:在Swift 2.3中重写

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

var window: UIWindow?

func applicationDidFinishLaunching(application: UIApplication) {
    UNUserNotificationCenter.currentNotificationCenter().delegate = self
    UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert]) { (granted, error) in
        if granted {
            self.registerCategory()
            self.scheduleNotification("test", interval: 3)
            self.scheduleNotification("test2", interval: 5)
        }
    }
}


func registerCategory() -> Void{

    let callNow = UNNotificationAction(identifier: "call", title: "Call now", options: [])
    let clear = UNNotificationAction(identifier: "clear", title: "Clear", options: [])
    let category : UNNotificationCategory = UNNotificationCategory.init(identifier: "CALLINNOTIFICATION", actions: [callNow, clear], intentIdentifiers: [], options: [])

    let center = UNUserNotificationCenter.currentNotificationCenter()
    center.setNotificationCategories([category])

}

func scheduleNotification(event : String, interval: NSTimeInterval) {
    let content = UNMutableNotificationContent()

    content.title = event
    content.body = "body"
    content.categoryIdentifier = "CALLINNOTIFICATION"
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: interval, repeats: false)
    let identifier = "id_"+event
    let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger)

    let center = UNUserNotificationCenter.currentNotificationCenter()
    center.addNotificationRequest(request) { (error) in

    }
}

func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {

    print("willPresent")
    completionHandler([.Badge, .Alert, .Sound])
}

func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {

    print("didReceive")
    completionHandler()
}

}

答案 1 :(得分:6)

对Swift 2.3使用belwo委托方法:

func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)

答案 2 :(得分:4)

确保您的AppDelegate实施UNUserNotificationCenterDelegate协议。

对于Swift

let center = UNUserNotificationCenter.current()
center.delegate = self

对于Objective-c

//set delegate to self
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];

将委托分配给self将触发以下方法。

// App in foreground
    private func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
      print("willPresent")
      }
//On Action click
     private func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
      print("didReceive")
      }

答案 3 :(得分:4)

我找到了答案。在使用Swift 2.3在Xcode 8上运行app并在iOS 9.3上运行最小部署目标时,会调用delegate方法。

func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)

在swift 3.0中使用,

func userNotificationCenter(_ center: UNUserNotificationCenter, 
                      didReceive response: UNNotificationResponse, 
           withCompletionHandler completionHandler: @escaping () -> Void)

参考:https://developer.apple.com/reference/usernotifications/unusernotificationcenterdelegate/1649501-usernotificationcenter

答案 4 :(得分:3)

根据Xtend-plugin

  

重要

     

您必须将代理对象分配给UNUserNotificationCenter   对象在您的应用程序完成启动之前不久。例如,在   iOS应用程序,您必须在applicationWillFinishLaunching( :)中分配它   或applicationDidFinishLaunching( :)方法。

因此,可能是设置通知中心代表太晚的问题。

答案 5 :(得分:2)

适用于Swift 3.0

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

    print("** willPresent")
    completionHandler([.badge, .alert, .sound])
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    print("** didReceive")
    completionHandler()
}

答案 6 :(得分:1)

您使用的功能签名不正确

swift中正确的函数签名是:

func userNotificationCenter(UNUserNotificationCenter, willPresent: UNNotification, withCompletionHandler: (UNNotificationPresentationOptions) -> Void) {

//your code here

}

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

//your code here

}

答案 7 :(得分:0)

文档说要在applicationWillFinishLaunching(:)或applicationDidFinishLaunching(:)中设置委托。因此,在AppDelegate中包含以下代码:

object person = Activator.CreateInstance(Type.GetType("Human.Person"));

设置此委托后,将调用以下willPresent函数。

IPerson person = (IPerson)Activator.CreateInstance(Type.GetType("Human.Person"));

答案 8 :(得分:0)

检查以确保仅将您的AppDelegate设置为UNUserNotificationCenter委托。

您在使用...

UNUserNotificationCenter.current().delegate = self

...不止一次?我试图通过在每个视图控制器中更改每个代理并使用每个函数来捕获具有不同结果的通知:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
   // code
}

对我来说,问题在于我尚未实现其功能,因此未调用AppDelegate中原始的userNotificationCenter函数“ didReceive”。这可能就是为什么您的电话没有被打电话的原因。

答案 9 :(得分:0)

我遇到了同样的问题。

更换

[UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateComponents repeats:NO];

[UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];

帮助了我。当然这可以做其他事情,但至少现在可以使用