我想知道是否有办法通过Unity中的C#脚本获取iOS设备的广告ID?
提前致谢。
答案 0 :(得分:2)
你无法单独使用C#,但你可以编写一个超级简单的插件来实现它。
创建一个名为getVendorId.mm的文件(或任何你想要命名的文件)并将此代码放入其中:
#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;
}
}
然后将该文件放入Assets&gt; Plugins&gt; iOS文件夹中。
然后在C#脚本中你要使用id,首先声明exturn方法如下:
#if UNITY_IPHONE
[DllImport("__Internal")]
private static extern string _getDeviceVendorId();
#endif
然后你可以像这样在那个脚本中的任何地方调用方法:
string AdvertisingId = _getDeviceVendorId();
答案 1 :(得分:0)
有一种更简单的跨平台方式,不需要编写任何插件。
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;
}