Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local Notification in WatchOS 3

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
        }


    }
like image 665
macgeezer Avatar asked Aug 13 '16 22:08

macgeezer


People also ask

Can Apple Watch 3 get notifications?

You can turn on an app's notifications if you want to see them again: Open the Apple Watch app on your iPhone, then tap the My Watch tab. Tap Notifications. Scroll down to the list of installed apps, then turn on the app that you want to receive notifications from.

Why is my notifications not showing on my Apple Watch?

Check Your Connection If you're not receiving notifications on your Apple Watch, there is a chance that it's because the watch has lost its connection with the iPhone. Before trying out any of the other steps, make sure that your Apple Watch is connected to your iPhone.

How do I get notifications on my Apple Watch home screen?

Tap My Watch, then tap Notifications. Tap the app (for example, Messages), tap Custom, then choose an option. Options may include: Allow Notifications: The app displays notifications in Notification Center.

Can I get notifications on both my phone and Apple Watch?

Notifications appear on your Apple Watch or iPhone, but not both. If your iPhone is unlocked, you get notifications on your iPhone instead of your Apple Watch. If your iPhone is locked or asleep, you get notifications on your Apple Watch, unless your Apple Watch is locked.


3 Answers

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)
like image 65
Owen Zhao Avatar answered Oct 29 '22 00:10

Owen Zhao


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)
like image 33
Ahmed Safadi Avatar answered Oct 29 '22 02:10

Ahmed Safadi


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;
}
like image 32
Ashish Avatar answered Oct 29 '22 02:10

Ashish