yzxhz

  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的,然后就可以注册方法了。

 

搞定~

 

相关文章: