unity是無法直接獲取ios設備信息的,但是unity可以與IOS代碼進行交互,這就可以完成你想要實現的功能了。
直接上代碼:
CheckCountry.h文件:
#import <Foundation/Foundation.h> @interface CheckCountry : NSObject + (int)_inChina; + (int)_isIOSPhone; +(bool)_IOS_IsInstallApp:(const char*)url; @end
CheckCountry.mm文件:
#import "CheckCountry.h" @implementation CheckCountry + (int)_inChina{ int in_china = 0; if([[[NSTimeZone localTimeZone] name] rangeOfString:@"Asia/Chongqing"].location == 0 || [[[NSTimeZone localTimeZone] name] rangeOfString:@"Asia/Harbin"].location == 0 || [[[NSTimeZone localTimeZone] name] rangeOfString:@"Asia/Hong_Kong"].location == 0 || [[[NSTimeZone localTimeZone] name] rangeOfString:@"Asia/Macau"].location == 0 || [[[NSTimeZone localTimeZone] name] rangeOfString:@"Asia/Shanghai"].location == 0 || [[[NSTimeZone localTimeZone] name] rangeOfString:@"Asia/Taipei"].location == 0) { in_china = 1; } return in_china; } + (int)_isIOSPhone{ int isIOSPhone = 0; if(TARGET_OS_IPHONE) { isIOSPhone = 1; } return isIOSPhone; } +(bool)_IOS_IsInstallApp:(const char*)url{ if (url == NULL) { return false; } NSURL *nsUrl = [NSURL URLWithString:[NSString stringWithUTF8String:url]]; if ([[UIApplication sharedApplication] canOpenURL:nsUrl]) { return true; } return false; } @end extern "C" { int _inChina() { return [CheckCountry _inChina]; } int _isIOSPhone() { return [CheckCountry _isIOSPhone]; } bool IOS_IsInstallApp(const char *url) { // return [CheckApp _IOS_IsInstallApp(url)]; return [CheckCountry _IOS_IsInstallApp:url]; } }
oc代碼主要分為兩個文件,一個,h 一個.mm 我也不知道是干嘛的,但是主要代碼在.mm中,.h里面的內容好像是供外部使用的。。。我胡說的吧,感興趣自己查一下~
在@end之前都是oc代碼,之后的代碼就是要傳入unity的方法了。
其中要注意的三點:
1.這兩個文件.mm和.h要放到unity的Assets=>Plugins=>IOS路徑里面。
2.不能直接傳String,要轉為char數組傳入。
3.oc中布爾值使用的是yes和no,我剛開始擔心不能直接傳布爾值,用的int 0/1代替,后來發現可以直接傳。。。
下面上unity代碼:
using System.Runtime.InteropServices; using UnityEngine; public class CheckRegion : MonoBehaviour { [DllImport("__Internal")] private static extern int _inChina(); public static int inChina() { return _inChina(); } [DllImport("__Internal")] private static extern bool IOS_IsInstallApp(string ss); public static bool iOS_IsInstallApp(string ss) { return IOS_IsInstallApp(ss); } [DllImport("__Internal")] private static extern int _isIOSPhone(); public static int isIOSPhone() { return _isIOSPhone(); } }
這里的代碼,首先要引用命名空間 using System.Runtime.InteropServices;
有了這個命名空間就可以使用 [DllImport(”“)] 標簽了。
這個標簽就是引用各種插件dll的,然后就可以注冊方法了。
搞定~