Hello,
If you want to invoke specific platform code, you can use Conditional compilation then execute these sepcific code directly in MAUI.
For example, you create a class that called GetDevice.cs like following code in the MAUI. You can use different namespaces for iOS and Android platform code, then execute the specific code that wrap Conditional compilation.
#if ANDROID
using static Android.Provider.Settings;
#elif IOS
using Foundation;
using System.Runtime.InteropServices;
#endif
namespace MauiApp1;
public class GetDevice
{
public string GetIdentifier()
{
string Identifier = "";
#if ANDROID
Identifier= Secure.GetString(Microsoft.Maui.ApplicationModel.Platform.CurrentActivity.ContentResolver, Secure.AndroidId);
#elif IOS
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
static extern uint IOServiceGetMatchingService(uint masterPort, IntPtr matching);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
static extern IntPtr IOServiceMatching(string s);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
static extern IntPtr IORegistryEntryCreateCFProperty(uint entry, IntPtr key, IntPtr allocator, uint options);
[DllImport("/System/Library/Frameworks/IOKit.framework/IOKit")]
static extern int IOObjectRelease(uint o);
string serial = string.Empty;
uint platformExpert = IOServiceGetMatchingService(0, IOServiceMatching("IOPlatformExpertDevice"));
if (platformExpert != 0)
{
NSString key = (NSString)"IOPlatformSerialNumber";
IntPtr serialNumber = IORegistryEntryCreateCFProperty(platformExpert, key.Handle, IntPtr.Zero, 0);
if (serialNumber != IntPtr.Zero)
{
serial = NSString.FromHandle(serialNumber);
//serial = UIDevice.CurrentDevice.IdentifierForVendor.ToString();
}
IOObjectRelease(platformExpert);
}
Identifier=serial;
#endif
return Identifier;
}
}
For example, When you want to get Identifier in the button click event. You can initialize this GetDevice.cs
and get value directly.
private async void Button_Clicked(object sender, EventArgs e)
{
#if ANDROID || IOS
GetDevice getDevice= new GetDevice();
var res=getDevice.GetIdentifier();
#endif
}
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.