Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any chance to "wrap" this native iOS API call into async / await?

Consider this iOS 6 API call:

eventStore.RequestAccess(EKEntityType.Event, (granted, error) => {
if(granted)
{
    events = this.GetLocalCalendarEvents(eventStore);
}});

I have some code that accesses the calendar and reads events. On iOS5 this just works but on iOS6 I have to ask for access first and, if granted, start reading then. I was wondering if I can somehow wrap this into a combination of async/await to hide the ugly delegate.

Any ideas?

like image 916
Krumelur Avatar asked Dec 18 '25 04:12

Krumelur


1 Answers

You can use TaskCompletionSource:

public Task<bool> DoSomethingAsync()
{
   var taskSource = new TaskCompletionSource<bool>();

   //Call some asynchronous Apple API
   NSSomeAppleApi.DoSomething(error =>
   {
      if (error != null)
         taskSource.SetException(new Exception(error.LocalizationDescription));
      else
         taskSource.SetResult(true);
   });

   return taskSource.Task;
}
like image 76
jonathanpeppers Avatar answered Dec 19 '25 18:12

jonathanpeppers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!