9

I am working on a project using Xamarin.iOS and I have a situation where a behavior in the simulator inexplicably is not the same on an actual device (setting the region of a mapview centers differently).

I want to be able to set a value for a variable at runtime based on whether the app is running on the simulator or a real device. How can I detect this?

Jason Hartley
  • 2,459
  • 1
  • 31
  • 40
  • If you know you are compiling for Simulator or Device target, why not check the compile time macro? There is no possible chance of running the same binary both on Simulator and Devices. See [Programmatically detect if app is being run on device or simulator](http://stackoverflow.com/questions/5775420/programmatically-detect-if-app-is-being-run-on-device-or-simulator) – Simon May 29 '13 at 03:01
  • The compile time answer would work if I could get it working for Xamarin/C#. Thanks. – Jason Hartley May 29 '13 at 04:19

2 Answers2

19

You can execute different code at runtime like this:

if (ObjCRuntime.Runtime.Arch == Arch.DEVICE) {
} else {
}

But it's always good to investigate (ask around here, forums, bug reports) why the behaviour differs between the two (just to make sure it does not hide a bug that could bite you later).

poupou
  • 43,413
  • 6
  • 77
  • 174
  • 1
    The `MonoTouch` namespace doesn't seem to apply. For example, with a `using ObjCRuntime;`, the simulation check becomes just `Runtime.Arch == Arch.SIMULATOR`. – Edward Brey Jun 04 '18 at 12:02
  • good catch, that's an old answer back when we were using the _classic_ (32bits only) API. Today with unified (32/64) we don't use the MonoTouch prefix anymore. – poupou Jun 12 '18 at 21:29
0

Something along this will do:

        public static bool Isiossimulator()
        {
            bool Return = false;
#if IOS
            if (DeviceInfo.DeviceType == DeviceType.Virtual)
                Return = true;
#endif
            return Return;
        }

Also make sure taking this approach is not to hide some bug.

ms2r
  • 170
  • 3
  • 17