How do I call UNUserNotificationCenter asynchronously?

Hi,

I'm trying to learn how to use asynchronous functions in Swift. I've used async functions in other languages such as C#, so I understand the general concept.

I want to call getPendingNotificationRequests on UNUserNotificationCenter asynchronously, so I wrote this:

    let notificationCenter = UNUserNotificationCenter.current()
    let requests = await notificationCenter.getPendingNotificationRequests()

This seems to match the examples I see in documentation, but it doesn't work. All I get is a compiler error that says "Missing argument for parameter 'completionHandler'". What am I doing wrong?

The documentation page is your friend here: https://developer.apple.com/documentation/usernotifications/unusernotificationcenter/1649524-getnotificationsettings

The getPendingNotificationRequests() function is imported by the Swift compiler from the Obj-C header files, but that function uses a completion handler even in Swift. In the Swift concurrency era, the Swift compiler also imports it under a modified name as an async function. Use the correct name, and you can use the function asynchronously.

That's what the yellow box on the above-linked page is telling you. :)

Note: For a bit of context, the Swift compiler is able to "transform" an Obj-C function with a completion handler into an async function because there's an underlying mechanism that does all the heavy lifting. You could make a transformed function yourself, but it'd just be some boilerplate that you'd have to write for every individual function you wanted to use, so Swift (specifically: the Obj-C header file import portion of Swift) does this for you.

You can read about how this works here: https://developer.apple.com/documentation/swift/checkedcontinuation/, as well as various WWDC videos that discuss Swift concurrency.

How do I call UNUserNotificationCenter asynchronously?
 
 
Q