1. 程式人生 > >U3D獲取IOS裝置所在時區、是否安裝指定APP、判斷真機還是模擬器

U3D獲取IOS裝置所在時區、是否安裝指定APP、判斷真機還是模擬器

  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的,然後就可以註冊方法了。

搞定~