When running our apps in development environment we often want to access some kind of backed service running on our development machine. It is simple on iOS simulator because it uses host machine network so we can reach our development machine with localhost or 127.0.0.1. On Android there is an alias 10.0.2.2 to your host loopback interface. But when running on device we have to use actual IP address of our machine in local network. A lot of different variations, right? Localhost allows us to use different IP address to access local development machine depending on the platform the app runs on. There are 4 supported platform variations: iOS simulator, iOS device, Android emulator and Android device. This library takes advantage of bait-and-switch pattern so it can be used from shared code.
Note that nuget package has to be installed in both PCL and platform specific projects.
[code language=”csharp” gutter=”false”]
// Get IP address for current platform variation
string ip = CrossLocalhost.Current.Ip;
// Set IP address that must be used when running on iOS simulator
// Set IP address that must be used when running on iOS device
// Set IP address that must be used when running on Android emulator
// Set IP address that must be used when running on Android device
These are the default values for each platform variation:
But you can override them like shown in API section.
So now we are able to define different IP addresses for each configuration variant in one place in PCL (or in platform-specific code if we want to). And by calling
CrossLocalhost.Current.Ip we will get the correct version based on the platform our app currently runs on.