Skip to content

Commit 5784b55

Browse files
committed
Added iOS UI dispatcher
1 parent 9482d16 commit 5784b55

1 file changed

Lines changed: 79 additions & 0 deletions

File tree

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// --------------------------------------------------------------------------------------------------------------------
2+
// <copyright file="UIDispatcher.iOS.cs" company="MADE Apps">
3+
// Copyright (c) MADE Apps.
4+
// </copyright>
5+
// <summary>
6+
// Defines a dispatcher that performs actions on the UI thread.
7+
// </summary>
8+
// --------------------------------------------------------------------------------------------------------------------
9+
10+
#if __IOS__
11+
namespace MADE.App.Views.Threading
12+
{
13+
using System;
14+
using System.Threading.Tasks;
15+
16+
using Foundation;
17+
18+
/// <summary>
19+
/// Defines a dispatcher that performs actions on the UI thread.
20+
/// </summary>
21+
public class UIDispatcher : IUIDispatcher
22+
{
23+
/// <summary>
24+
/// Gets the platform specified UI object to use as a reference.
25+
/// </summary>
26+
public object Reference { get; private set; }
27+
28+
private NSObject NSObject => this.Reference as NSObject;
29+
30+
/// <summary>
31+
/// Sets the <see cref="Foundation.NSObject"/> to use as a reference for dispatching actions on the UI thread.
32+
/// </summary>
33+
/// <param name="reference">
34+
/// The <see cref="Foundation.NSObject"/> object.
35+
/// </param>
36+
public void SetReference(object reference)
37+
{
38+
this.Reference = null;
39+
40+
if (!(reference is NSObject activity))
41+
{
42+
return;
43+
}
44+
45+
this.Reference = activity;
46+
}
47+
48+
/// <summary>
49+
/// Schedules the provided action on the UI thread from a worker thread.
50+
/// </summary>
51+
/// <param name="action">
52+
/// The action to run on the dispatcher.
53+
/// </param>
54+
/// <returns>
55+
/// An asynchronous operation.
56+
/// </returns>
57+
public async Task RunAsync(Action action)
58+
{
59+
UIDispatcher dispatcher = this;
60+
dispatcher.CheckInitialized();
61+
if (action == null)
62+
{
63+
return;
64+
}
65+
66+
await Task.Run(() => { this.NSObject?.InvokeOnMainThread(action); });
67+
}
68+
69+
private void CheckInitialized()
70+
{
71+
if (this.Reference == null)
72+
{
73+
throw new InvalidOperationException(
74+
"Cannot run an action as the NSObject has not be set as the reference in the SetReference method.");
75+
}
76+
}
77+
}
78+
}
79+
#endif

0 commit comments

Comments
 (0)