2

I'd like to know if there's a way to get the advertising ID for an iOS device through a C# script in Unity ?

Thanks in advance.

azekirel555
  • 577
  • 2
  • 8
  • 25

2 Answers2

2

You can't get it with C# alone, but you can write a super simple plugin to do it.

Create a file named getVendorId.mm (or whatever you want to name it) and put this code in it:

    #import <AdSupport/ASIdentifierManager.h>

extern "C"
{
    char* _getDeviceVendorId()
    {
        NSUUID *adId = [[ASIdentifierManager sharedManager] advertisingIdentifier];
        NSString *udid = [adId UUIDString];
        const char *converted = [udid UTF8String];
        char* res = (char*)malloc(strlen(converted) + 1);
        strcpy(res, converted);
        return res;
    }
}

Then put that file in your Assets>Plugins>iOS folder.

Then in the C# script you want to use the id in, first declare the exturn method like so:

#if UNITY_IPHONE
        [DllImport("__Internal")]
        private static extern string _getDeviceVendorId();
#endif

Then you can just call the method anywhere in that script like so:

string AdvertisingId = _getDeviceVendorId();
turnipinrut
  • 614
  • 4
  • 12
1

There's a simpler cross-platform way that doesn't require writing any plugins.

public Task<string> GetIDFA()
    {
        var tcs = new TaskCompletionSource<string>();

        if (!Application.RequestAdvertisingIdentifierAsync((idfa, enabled, error) =>
        {
            if (!string.IsNullOrEmpty(error))
            {
                taskCompletionSource.SetException(new Exception(error));
            }
            else if (!enabled)
            {
                taskCompletionSource.SetException(new NotSupportedException("User has disabled advertising tracking"));
            }
            else
            {
                taskCompletionSource.SetResult(idfa);
            }
        }))
        {
            throw new NotSupportedException("Advertising is not supported");
        }

        return taskCompletionSource.Task;
    }
Shpand
  • 661
  • 9
  • 14
  • 1
    Note that this will stop working for android in Unity 2020.1 https://stackoverflow.com/questions/63693346/how-to-get-google-advertising-id-in-unity-2020-1 – Patrick Fay Mar 12 '21 at 04:29