Local Notification in WatchOS 3

时间秒杀一切 提交于 2019-12-09 18:01:15

问题


I'm using the WatchOS 3 beta and trying to initiate a local notification on the watch. The interface is just one button which calls the "buttonPushed" method in the code below. The app runs fine but I never get a notification. The app structure is the default from Xcode 8 for a WatchKit app.

This code is in the InterfaceController.swift file of the WatchKit extension

Am I missing something totally obvious?

@IBAction func buttonPushed() {
        sendMyNotification()
    }

    func sendMyNotification(){
        if #available(watchOSApplicationExtension 3.0, *) {

            let center = UNUserNotificationCenter.current()

            center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
                // Enable or disable features based on authorization.
            }


            let content = UNMutableNotificationContent()
            content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
            content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
            content.sound = UNNotificationSound.default()
            content.categoryIdentifier = "REMINDER_CATEGORY"
            // Deliver the notification in five seconds.
            let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
            let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)

            // Schedule the notification.

            center.add(request ,withCompletionHandler: nil)



        } else {
            // Fallback on earlier versions
        }


    }

回答1:


According to this. You should specify a unique and new identifier for request each time.

Mine:

let id = String(Date().timeIntervalSinceReferenceDate)
let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)



回答2:


Swift 4 simple code

    let content = UNMutableNotificationContent()
    content.title = "How many days are there in one year"
    content.subtitle = "Do you know?"
    content.body = "Do you really know?"
    content.badge = 1

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)



回答3:


Local Notification watchOS swift 4.0

var content = UNMutableNotificationContent()
content.title = "ALERT !"
content.body = msg
content.sound = UNNotificationSound.default() as? UNNotificationSound
// Time
var trigger: UNTimeIntervalNotificationTrigger?
trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
// Actions
var snoozeAction = UNNotificationAction(identifier: "Track", title: "Track", options: .foreground)

var category = UNNotificationCategory(identifier: "UYLReminderCategory", actions: [snoozeAction], intentIdentifiers: [] as? [String] ?? [String](), options: .customDismissAction)
var categories = Set<AnyHashable>([category])

center.setNotificationCategories(categories as? Set<UNNotificationCategory> ?? Set<UNNotificationCategory>())

content.categoryIdentifier = "UYLReminderCategory"

var identifier: String = stringUUID()

var request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

center.add(request, withCompletionHandler: {(_ error: Error?) -> Void in
if error != nil {
    print("Something went wrong: \(error)")
}
})

Unique request identifier methods

func stringUUID() -> String {
     let uuid = UUID()
     let str: String = uuid.uuidString
     return str
}

Objective C

 // Objective-C
   UNMutableNotificationContent *content = [UNMutableNotificationContent new];
   content.title = @"ALERT !";
   content.body = msg;
   content.sound = [UNNotificationSound defaultSound];

// Time

   UNTimeIntervalNotificationTrigger *trigger;

   trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1
                                                                                                repeats:NO];
// Actions
   UNNotificationAction *snoozeAction = [UNNotificationAction actionWithIdentifier:@"Track"
                                                                          title:@"Track" options:UNNotificationActionOptionForeground];

// Objective-C
  UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"UYLReminderCategory"
                                                                          actions:@[snoozeAction] intentIdentifiers:@[]
                                                                          options:UNNotificationCategoryOptionCustomDismissAction];
   NSSet *categories = [NSSet setWithObject:category];

// Objective-C
   [center setNotificationCategories:categories];

// Objective-C
    content.categoryIdentifier = @"UYLReminderCategory";

    NSString *identifier = [self stringUUID];
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
                                                                      content:content trigger:trigger];

    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    if (error != nil) {
        NSLog(@"Something went wrong: %@",error);
    }
    }];

Unique request identifier methods

-(NSString *)stringUUID {
   NSUUID *uuid = [NSUUID UUID];
   NSString *str = [uuid UUIDString];
   return str;
}


来源:https://stackoverflow.com/questions/38937385/local-notification-in-watchos-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!