- 在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
#import "MyTool.h"
@implementation MyTool
+ (const char *) getCountryCode{
NSLocale *currentLocale = [NSLocale currentLocale];
NSString *countryCode = [currentLocale objectForKey:NSLocaleCountryCode];
const char *country = [countryCode UTF8String];
return country;
}
@end
extern "C"{
const char *getCountryCode(){
const char* cString = [MyTool getCountryCode];
return cString;
}
}
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()}");
}
}