skip to Main Content

In my .NET8 MAUI application, I have a few functions for every platform but most of the code is the same. I saw somewhere that I could do something like:

#if iOS
    public async Task<string> Register(NSData rawToken)
    {
        var nativeToken = rawToken.ToPushTokenString();
#endif
#if ANDROID
    public async Task<string> Register(string nativeToken)
    { 
#endif
        // code
    }

I tried but Visual Studio disagrees and gets me an error. Is there any particular configuration I have to change? How does this pre-processor command work?

Update

The errors are:

  • CS1519 Invalid token ‘return’ in class, record, struct, or interface member declaration
  • CS1022 Type or namespace definition, or end-of-file expected

enter image description here

2

Answers


  1. Try to change your code:

    #if iOS
    public async Task<string> Register(NSData rawToken)
    {
        var nativeToken = rawToken.ToPushTokenString();
        // code...
    }
    #elif ANDROID
    public async Task<string> Register(string nativeToken)
    { 
        // code
    }
    #endif
    

    Maybe you have to think about other build configurations also (WINDOWS, for example).

    Login or Signup to reply.
  2. I would refactor the code to use partial classes instead of what you have right now.

    
    namespace LanguageInUse.Services.PartialMethods
    {
        public partial class DeviceInstallation
        {
            public async Task<string> Register(string token);
        }
    }
    
    

    android:

    namespace LanguageInUse.Services.PartialMethods
    {
        public partial class DeviceInstallation
        {
            public async Task<string> Register(string token) {
                // do something
            }
        }
    }
    
    

    ios:

    namespace LanguageInUse.Services.PartialMethods
    {
        public partial class DeviceInstallation
        {
            public async Task<string> Register(string token) {
                var nativeToken = NSData.FromString(token).ToPushTokenString();
                // do something
            
            }
        }
    }
    
    

    make sure your namespaces are same across all. With this you don’t need to add these if everywhere. Because currently how it’s setup you need to add #if iOS everywhere to send an NSData and so on.

    https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/invoke-platform-code?view=net-maui-8.0

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search