Search code examples
androidmacos.net-corexamarin.formsrider

Xamarin - unable to access local api via Android (and iOS)


I'm using macos Rider to develop a Xamarin app for Android and iOs. I have a local api that I'm trying to use via the app, but it appears that the app cannot reach the api. This happens on Android as well as on iOS.

Focussing on Android, I have tried changing the api to http://10.0.2.2:5000. The thing is, I can access the api endpoints when using the emulators browser, but trying to do so via the app, it gets stuck on loading.

When using the iPhone emulator, I get the error that I should use SSL in order to access the api via the emulator.

I've tried to debug on Android in order to find out whether the api is actually the issue here (I find it weird that I can access it via the emulators browser), but I'm unable to figure it out because there is no exception thrown. When reaching the code below, it appears as if it simply 'stops'. enter image description here

To sum it up, some facts:

  1. The app breaks down on iOS and Android
  2. The api is running, and I've tried http://10.0.2.2:5000 for Android, http://localhost:5000 for iPhone. I can reach the app via both emulators browsers and via Postman. This gives me results as well, so nothing appears to be wrong with the database or the api for that matter.
  3. I'm using a Mac (Jetbrains Rider)
  4. It does work when I use the same api that is running on a server

Solution

  • If you want to access HTTP connections to any site , You need to add the following code in specific platform

    in iOS

    Add the following lines to info.plist

    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    

    in Android

    Add the line android:usesCleartextTraffic="true" to AndroidManifest like following

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"   android:versionCode="1" android:versionName="1.0" package="com.companyname.app32">
        <uses-sdk android:minSdkVersion="21"  android:targetSdkVersion="28"  />
        <application android:label="App32.Android" android:theme="@style/MainTheme" android:usesCleartextTraffic="true"></application>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    </manifest>