azekirel555
azekirel555

Reputation: 587

How do I get the advertising ID for an iOS device in C#?

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.

Upvotes: 2

Views: 1318

Answers (2)

Shpand
Shpand

Reputation: 751

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;
    }

Upvotes: 1

turnipinrut
turnipinrut

Reputation: 614

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();

Upvotes: 2

Related Questions