原地址:http://dong2008hong.blog.163.com/blog/static/469688272014021025578/
在前一段時間游戲開發中需要實現獲取IOS設備所在的國家代碼,方便服務端推送合適的語言的功能,在網上找了一些資料實現了上述功能,現在分享給大家。后面會給大家分享網絡編程、數據庫的應用、服務器的配置等的一些知識和注意事項。 首先,這個功能Unity是沒有提供現成的API,所以必須先制作一個IOS插件,然后才再Unity里面來調用Object-c實現了的功能。 MyTool.h文件代碼: #import <Foundation/Foundation.h> @interface MyTools : NSObject @end MyTool.m文件代碼: #import "MyTools.h" @implementation MyTools char *_getCountryCode(){ NSLocale *locale = [NSLocalecurrentLocale]; NSString *countrycode = [localelocaleIdentifier]; NSLog(@"國家代碼:%@",countrycode); const char *country = [countrycodeUTF8String]; char *back =malloc(countrycode.length + 1); char *back2 = back; for (int i = 0;i<countrycode.length; i++) { *back2 = country; back2++; } *back2 = '\0'; return back; } @end 插件制作好以后,放到Plugins/IOS文件夾下,然后在Unity中創建MyTools.cs腳本 代碼如下: using UnityEngine; using System.Collections; using System.Runtime.InteropServices; public class MyTools : MonoBehaviour { [DllImport("__Internal")] private static extern string _getCountryCode(); public static string getCountryCode() { return _getCountryCode(); } } 在制作插件的時候一定要注意的問題就是,Object-c是不能直接傳NSString數據類型給Unity的,你必須把NSString類型轉化成char[]傳給Unity。