IosAppTrackingService.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using UnityEngine;
  5. #if UNITY_IOS && !UNITY_EDITOR
  6. using Unity.Advertisement.IosSupport;
  7. #endif
  8. /// <summary>Runs the iOS ATT dialog once before SDKs that may read IDFA are initialized.</summary>
  9. public static class IosAppTrackingService
  10. {
  11. static bool completed;
  12. static bool inFlight;
  13. static SynchronizationContext mainThreadContext;
  14. static int mainThreadId;
  15. static readonly List<Action> pendingCallbacks = new List<Action>();
  16. public static bool IsCompleted => completed;
  17. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
  18. static void ResetStatics()
  19. {
  20. completed = false;
  21. inFlight = false;
  22. mainThreadContext = null;
  23. mainThreadId = 0;
  24. pendingCallbacks.Clear();
  25. }
  26. public static void RunOnce(Action onComplete)
  27. {
  28. if (onComplete == null)
  29. return;
  30. if (completed)
  31. {
  32. onComplete();
  33. return;
  34. }
  35. if (mainThreadContext == null)
  36. {
  37. mainThreadContext = SynchronizationContext.Current;
  38. mainThreadId = Thread.CurrentThread.ManagedThreadId;
  39. }
  40. pendingCallbacks.Add(onComplete);
  41. if (inFlight)
  42. return;
  43. #if UNITY_IOS && !UNITY_EDITOR
  44. if (Application.platform != RuntimePlatform.IPhonePlayer)
  45. {
  46. Complete();
  47. return;
  48. }
  49. var status = ATTrackingStatusBinding.GetAuthorizationTrackingStatus();
  50. if (status != ATTrackingStatusBinding.AuthorizationTrackingStatus.NOT_DETERMINED)
  51. {
  52. Debug.Log("[ATT] Tracking authorization status is already determined: " + status);
  53. Complete();
  54. return;
  55. }
  56. inFlight = true;
  57. Debug.Log("[ATT] Requesting App Tracking Transparency authorization.");
  58. ATTrackingStatusBinding.RequestAuthorizationTracking(CompleteRequest);
  59. #else
  60. Complete();
  61. #endif
  62. }
  63. #if UNITY_IOS && !UNITY_EDITOR
  64. static void CompleteRequest(int status)
  65. {
  66. Debug.Log("[ATT] Authorization request completed with status: " + status);
  67. SynchronizationContext context = mainThreadContext;
  68. if (Thread.CurrentThread.ManagedThreadId != mainThreadId && context != null)
  69. {
  70. context.Post(_ => Complete(), null);
  71. return;
  72. }
  73. Complete();
  74. }
  75. #endif
  76. static void Complete()
  77. {
  78. completed = true;
  79. inFlight = false;
  80. var callbacks = pendingCallbacks.ToArray();
  81. pendingCallbacks.Clear();
  82. foreach (Action callback in callbacks)
  83. callback?.Invoke();
  84. }
  85. }