iosswifttvosusernotifications

Exclude notification methods for tvOS using @available


I'm studying UserNotifications framework and have the following method to respond to user's actions on a notification.

func userNotificationCenter (_ pNotificationCenter: UNUserNotificationCenter, didReceive pResponse: UNNotificationResponse, withCompletionHandler pCompletionHandler: @escaping () -> Void) -> Void {
    ...
}

This works well in iOS and iPadOS, but the documentation says this delegate method is not applicable for tvOS - which leads me to believe that notification banners cannot be displayed in tvOS - which is ok.

But the problem is, how do I make this compile for tvOS? I'm getting the following error

error: 'UNNotificationResponse' is unavailable in tvOS
...
error: cannot override 'userNotificationCenter' which has been marked unavailable

I tried using the @available attribute, which would include this method only for iOS and iPadOS 10.0 and above.

@available(iOS 10.0, *)

But this doesn't work. I still get the same error. Macros can work, but what's wrong in the way I've used @available?

How do I selectively disable this function for tvOS using @available?

Update1: Even if I wrap the empty function as shown below, I still get the same error.

#if os(tvOS)
func userNotificationCenter (_ pNotificationCenter: UNUserNotificationCenter, didReceive pResponse: UNNotificationResponse, withCompletionHandler pCompletionHandler: @escaping () -> Void) -> Void {

}    
#endif

Update2: Silly mistake in update 1. If I need the above code to be available only for iOS and iPadOS, I should have used

#if os(iOS)

instead of

#if os(tvOS)

Solution

  • You declare the function if you have os(tvOS) but you want the function declared only if you have it not. In the conditional compilation you have not a direct negation. So a solution would be:

    #if os(tvOS)
        
    #warning("Not implemented in tvOS") // or if you want #error(...)    
            
    #else
            
    func userNotificationCenter (_ pNotificationCenter: UNUserNotificationCenter, didReceive pResponse: UNNotificationResponse, withCompletionHandler pCompletionHandler: @escaping () -> Void) -> Void {
    ....
    
    }
    

    So the function is only declared if you don't have tvOS.

    Here you find some more examples on conditional compilation but you find a lot more in the web...