Unity 获取设备的国家码 IOS

  • 在Unity的Assets/Plugins/iOS目录下新建一个MyTool文件夹
    在这里插入图片描述
  • 在MyTool文件夹下面新建两个同名的文件,一个后缀为.h,另一个后缀为.mm;分别为 MyTool.h,MyTool.mm
    在这里插入图片描述
  • MyTool.h的内容如下:
#import <Foundation/Foundation.h>
@interface MyTool : NSObject
 + (const char *) getCountryCode;
@end
  • MyTool.mm的内容如下:
#import "MyTool.h"
@implementation MyTool
+ (const char *) getCountryCode{
    
    
    // 获取当前地区的语言代码
    NSLocale *currentLocale = [NSLocale currentLocale];
    NSString *countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
    
    // 将语言代码转换为C字符串
    const char *country = [countryCode UTF8String];
    
    // 返回国家代码
    return country;
}
@end

extern "C"{
    
    
    const char *getCountryCode(){
    
    
        const char* cString = [MyTool getCountryCode];
        // 返回国家代码
        return cString;
    }
}
  • C#中调用:
using System;
using System.Runtime.InteropServices;

public class SDKIOS
{
    
    
	#if UNITY_IOS
	    [DllImport("__Internal")]
	    private static extern IntPtr getCountryCode();
	#endif
	
	    public override string GetCountryCode()
	    {
    
    
	#if UNITY_IOS
	            IntPtr countryCodePtr = getCountryCode();
	            string countryCode = Marshal.PtrToStringAnsi(countryCodePtr);
	            return countryCode;
	#else
	        return System.Globalization.RegionInfo.CurrentRegion.TwoLetterISORegionName;
	#endif
	}
	
	private void Start()
	{
    
    
		Debug.Log($"获取到的IOS国家码为:{
      
      GetCountryCode()}");
	}
}

猜你喜欢

转载自blog.csdn.net/u011229164/article/details/131845544