Call native iOS in UNO in button click event handler

Hi,

How would one use Uno in a project to call this iOS code

  • (IBAction) playSystemSound: (id) sender {

    AudioServicesPlaySystemSound (1100); }

In a button click handler?

Best regards

Hi!

To call Uno methods from UX markup instead of JS, you simply drop the {} brackets:

<Button Clicked="MethodName" />

And in your code behind .ux.uno file:

public partial class NameOfClass
{
    void MethodName(object sender, Uno.EventArgs args)
    {
        iOS.AudioToolbox.Functions.AudioServicesPlaySystemSound(1100);
    }
}

Make sure you add reference to the iOS and ObjC packages in your project.

Hi,

That sure looks simple :smiley: When I try to buil dI get this error:

iOS.AudioToolbox does not contain type or namespace ‘AudioServicesPlaySystemSound’. Could you be missing a package reference?

Any ideas?

Best Kenneth

Ah, whops, i forgot the static Functions class there. I’ve updated my above post

Hmm strange now it just says iOS.AudioToolbox does not contain type or namespace ‘Functions’

Hi!

Since we are dealing with platform specific code we need to add some more stuff here to get it to work :slight_smile:

Platform specific code can be mixed with platform agnostic code quite easily in UNO. Ill show you some examples for your case :slight_smile:

public partial class NameOfClass
{
        extern (!Mobile) void MethodName(object sender, Uno.EventArgs args)
        {
            // Do some non mobile stuff :)
        }

        extern (Android) void MethodName(object sender, Uno.EventArgs args)
        {
            // Do some android stuff
        }

        extern (iOS) void MethodName(object sender, Uno.EventArgs args)
        {
            global::iOS.AudioToolbox.Functions.AudioServicesPlaySystemSound(1100);
        }
}

In the above example only the method with the appropirate condition for you export target will be included in the compile. So if you build for iOS then only the method with extern (iOS) will be included.

Another easy way:

public partial class NameOfClass
{
        void MethodName(object sender, Uno.EventArgs args)
        {
              if !defined(Mobile)
              {
                  // Do some non mobile stuff :)    
              }
              else if defined(Android)
              {
                  // Do some android stuff
              }
              else if defined(iOS)
              {
                  global::iOS.AudioToolbox.Functions.AudioServicesPlaySystemSound(1100);    
              }
        }
}

Try this and get back to me if it didnt work :slight_smile:

That worked!! Thanks a lot, I have made a gist with a project demo of it for other people finding this thread: https://gist.github.com/kfiil/d5bd1d4a046d3af9e51a

Good stuff :slight_smile: