LoginSignup
0
0

【Unity】Swift のネイティブプラグインに options を渡す方法

Last updated at Posted at 2023-12-21

本記事について

この記事は CoreBluetoothForUnity Advent Calendar 2023 の22日目の記事です。

CoreBluetooth ではいくつかのメソッドにおいてオプションを渡すことができます。

init(delegate:queue:options:)

init(
    delegate: CBCentralManagerDelegate?,
    queue: dispatch_queue_t?,
    options: [String : Any]? = nil
)

このような文字列キーの辞書を Unity からネイティブプラグインに渡す方法を説明します。

実装

CBCentralManagerInitOptions

CBCentralManagerInitOptions.cs
public class CBCentralManagerInitOptions
{
    public static readonly string ShowPowerAlertKey = "kCBInitOptionShowPowerAlert";
    public bool? ShowPowerAlert { get; set; } = null;

    public CBCentralManagerInitOptions()
    {
    }

    internal NSMutableDictionary ToNativeDictionary()
    {
        var dict = new NSMutableDictionary();
        if (ShowPowerAlert.HasValue)
        {
            using var value = new NSNumber(ShowPowerAlert.Value);
            dict.SetValue(ShowPowerAlertKey, value.Handle);
        }
        return dict;
    }
}
CBCentralManager.cs
public CBCentralManager(ICBCentralManagerDelegate centralDelegate = null, CBCentralManagerInitOptions options = null)
{
    if (options == null)
    {
        _handle = SafeNativeCentralManagerHandle.Create();
    }
    else
    {
        using var optionsDict = options.ToNativeDictionary();
        _handle = SafeNativeCentralManagerHandle.Create(optionsDict.Handle);
    }
...
}

Options クラスから ToNativeDictionaryNSMutableDictionary を生成し、そのハンドルを渡しています。
using によって使い終わったらすぐ破棄しています。

ポイント

キー名の調べ方

ドキュメントに載っていないため、print で出力しました。

動的に取得していない理由は、定数を取得するためだけのコードを書くのが手間だったためです。

NSMutableDictionary

NSMutableDictionary.cs

インスタンス作成と同時にアンマネージドなオブジェクトを生成し、インスタンスメソッドによって更新しています。

IDictionary等のインタフェースについては得に必要ではなかったため実装していません。

参考

Xamarin の DictionaryContainer Class

おわりに

Foundation について知る前は、どうやってやるのか分かりませんでしたが知った後は割とすんなりできました。
汎用的な仕組みだと思うため、もし似たようなケースあればぜひ利用してみてください!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0