Exclude notification delegate methods for tvOS using @available

UserNotifications framework helps the app to handle all notification related aspects. The userNotificationCenter(_:didReceive:withCompletionHandler:) delegate method is used to handle user's action (dismiss, selected button, tap, text input etc.). As evident from the documentation, this method is available in iOS and iPadOS but not tvOS.

The @available attribute is one way to exclude methods.

@available(iOS 10.0, *)
func userNotificationCenter (_ pNotificationCenter: UNUserNotificationCenter, didReceive pResponse: UNNotificationResponse, withCompletionHandler pCompletionHandler: @escaping () -> Void) -> Void {
    // Handle user's action on a notification.
    ...
}

When the delegate method is declared as above, I expect it to be included only for iPadOS and iOS. When building for tvOS, I get the following error:

error: 'UNNotificationResponse' is unavailable in tvOS

error: cannot override 'userNotificationCenter' which has been marked unavailable

Clearly, it is included for tvOS also.

Another approach is using

#if os(iOS)

and it does work... I don't get the above errors, meaning the code is not included for tvOS. But I want to understand how to achieve this using @available attribute because I have other situations where I need to exclude methods for certain versions of the same OS.

How do I exclude userNotificationCenter(_:didReceive:withCompletionHandler:) for tvOS using @available attribute?

Answered by GangOrca in 752472022

After reading this post in swift forums about #if, @available and #available, I see that in this case, #if must be used... since any version of tvOS should not see the userNotificationCenter(_:didReceive:withCompletionHandler:) delegate method.

Accepted Answer

After reading this post in swift forums about #if, @available and #available, I see that in this case, #if must be used... since any version of tvOS should not see the userNotificationCenter(_:didReceive:withCompletionHandler:) delegate method.

Exclude notification delegate methods for tvOS using @available
 
 
Q