Error with httpClient.PostAsync in iOS project only.

If I comment out my try/catch for the connecting to the API, this is error that I receive is (from line 75 "var postResult = await httpClient.PostAsync(WebAPI, httpContent);"): Newtonsoft.Json.JsonReaderException:
I have used Postman connecting to my web API and put in the JSON string it builds and everything comes back fine. Is there maybe a permission for accessing the internet in iOS that I missed? If so, what permission do I add? I am using Visual Studio 2017 in Windows 10, Newtonsoft.Json version 12.0.1

using System;
using MyApp.Models;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using MyApp.Views.DetailViews;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace MyApp.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class LoginPage : ContentPage
    {
        private const string WebAPI = "my server address";


        public LoginPage()
        {
                InitializeComponent();
                Init();
        }

        #region Init

        void Init()
        {
            BackgroundColor = Constants.BackgroundColor;
            Lbl_Username.TextColor = Constants.MainTextColor;
            Lbl_Password.TextColor = Constants.MainTextColor;
            ActivitySpinner.IsVisible = false;
            LoginIcon.HeightRequest = Constants.LoginIconHeight;
            App.StartCheckIfInternet(lbl_NoInternet, this);

            Entry_Username.Completed += (object sender, EventArgs e) =>
            {
                Entry_Password.Focus();
            };
            Entry_Password.Completed += (object sender, EventArgs e) =>
            {
                SignInProcAsync(sender,e);
            };
        }
        #endregion

        #region Sign In Procedure
        public async void SignInProcAsync(object sender, EventArgs e)
        {
            try
            {
                //Check for NULL Email and Password
                if (!string.IsNullOrWhiteSpace(Entry_Username.Text) && !string.IsNullOrWhiteSpace(Entry_Password.Text))
                {
                    //Show activity spinner and drop User table, to refresh user data.
                    ActivitySpinner.IsVisible = true;
                    App.UserDatabase.DropTable();

                    //Check user settings
                    if (App.SettingsDatabase.GetSettings() == null)
                    {
                        Settings settings = new Models.Settings();
                        App.SettingsDatabase.SaveSettings(settings);
                    }

                    try
                    {
                        //Connect to API, send JSON file and get post back user JSON file.
                        var httpClient = new HttpClient();
                        var jsonObject = new List<AuthUser>();
                        jsonObject.Add(new AuthUser() { Email = Entry_Username.Text, Password = Entry_Password.Text });
                        string json = JsonConvert.SerializeObject(jsonObject);
                        HttpContent httpContent = new StringContent(json);
                        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        var postResult = await httpClient.PostAsync(WebAPI, httpContent);//Error occurs here only in iOS, UWP and Android works great.
                        var returnJson = await postResult.Content.ReadAsStringAsync();
                        var taskModel = JsonConvert.DeserializeObject<User>(returnJson);
                        App.UserDatabase.AddNewUser(taskModel.Email, taskModel.RoleCode, taskModel.DisplayName, taskModel.AcctNumb, taskModel.DepartmentID, taskModel.UserID);

                        //Check error message
                        if (App.UserDatabase.StatusMessage == 1)
                        {
                            ActivitySpinner.IsVisible = false;
                            await DisplayAlert("Login", "Invalid email and/or password.", "Ok");
                        }
                        else
                        {
                            ActivitySpinner.IsVisible = false;
                            await Navigation.PushModalAsync(new NavigationPage(new HomePage()));
                        }
                    }
                    catch
                    {
                        ActivitySpinner.IsVisible = false;
                        await DisplayAlert("Login", "A error has occurred connecting to server.", "Ok");
                    }



                }
                else
                {
                    ActivitySpinner.IsVisible = false;
                    await DisplayAlert("Login", "Email and/or Password must be entered.", "Ok");
                }
        }
            catch
            {
                ActivitySpinner.IsVisible = false;
                await DisplayAlert("Login", "An error has occurred.", "Ok");
    }

}
        #endregion
    }
}

Best Answers

  • LeonardChurchLeonardChurch ✭✭
    Accepted Answer

    Visual Studio 2017 Version 15.9.3
    Xamarin 4.12.3.73
    Xamarin Designer 4.16.5
    Xamarin Templates 1.1.127
    Xamarin.Android SDK 9.1.0.38
    Xamarin.iOS and Xamarin.Mac SDK 12.2.1.11

Answers

  • jonjackson17jonjackson17 Unconfirmed, Member, Xamarin Team Xamurai

    Can you check your Xamarin version in Visual Studio? There were a couple of service updates that went out.

  • LeonardChurchLeonardChurch Member ✭✭
    Accepted Answer

    Visual Studio 2017 Version 15.9.3
    Xamarin 4.12.3.73
    Xamarin Designer 4.16.5
    Xamarin Templates 1.1.127
    Xamarin.Android SDK 9.1.0.38
    Xamarin.iOS and Xamarin.Mac SDK 12.2.1.11

  • jonjackson17jonjackson17 Unconfirmed, Member, Xamarin Team Xamurai

    @LeonardChurch It seems you are up to date, I recommend going through these steps to see if something maybe preventing your permissions.
    https://stackoverflow.com/questions/29894749/complete-list-of-ios-app-permissions

  • My info.plist. Does it look like anything is missing?

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>UIDeviceFamily</key>
        <array>
            <integer>1</integer>
            <integer>2</integer>
        </array>
        <key>UISupportedInterfaceOrientations</key>
        <array>
            <string>UIInterfaceOrientationPortrait</string>
            <string>UIInterfaceOrientationLandscapeLeft</string>
            <string>UIInterfaceOrientationLandscapeRight</string>
        </array>
        <key>UISupportedInterfaceOrientations~ipad</key>
        <array>
            <string>UIInterfaceOrientationPortrait</string>
            <string>UIInterfaceOrientationPortraitUpsideDown</string>
            <string>UIInterfaceOrientationLandscapeLeft</string>
            <string>UIInterfaceOrientationLandscapeRight</string>
        </array>
        <key>MinimumOSVersion</key>
        <string>8.0</string>  
        <key>CFBundleDisplayName</key>
        <string>MyApp</string>  
        <key>CFBundleIdentifier</key>
        <string>com.domain.MyApp</string>  
        <key>CFBundleVersion</key>
        <string>1.0</string>  
        <key>UILaunchStoryboardName</key>
        <string>LaunchScreen</string>  
        <key>CFBundleName</key>
        <string>MyApp</string>  
        <key>XSAppIconAssets</key>
        <string>Assets.xcassets/AppIcon.appiconset</string>  
        <key>XSLaunchImageAssets</key>
        <string>Assets.xcassets/LaunchImages.launchimage</string>  
      <key>NSLocationWhenInUseUsageDescription</key>
      <string>This app would like to get you location when submitting</string>  
      <key>NSCameraUsageDescription</key>
      <string>This app would like to use you camera</string>  
      <key>NSPhotoLibraryUsageDescription</key>
      <string>This app would like to open your photos</string>
      <key>NSAppTransportSecurity</key>
      <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
      </dict>
    </dict>
    </plist>
    
  • jonjackson17jonjackson17 Unconfirmed, Member, Xamarin Team Xamurai

    @LeonardChurch nothing that I can validate. Are you able to retrieve your log file?

  • Which log file? :smile:

  • jonjackson17jonjackson17 Unconfirmed, Member, Xamarin Team Xamurai

    To get full build logs just set the log verbosity to diagnostic at the following locations:

    On Visual Studio for Mac: Preferences > Projects > Build
    On Visual Studio for Windows: Tools > Options > Projects and Solutions > Build and Run
    On Visual Studio Windows you also want to add -v -v -v -v to the mtouch additional arguments by right-clicking the project in the solution explorer and selecting Properties.
    Note: this is done automatically on Visual Studio for Mac when the log verbosity is set to diagnostic.

  • This is the output file after just running. Let me know if this is not what you are talking about.

  • LeonardChurchLeonardChurch Member ✭✭

    I also found that on my server IPv6 was enabled and the SSL cert was not on that side. I disabled IPv6 and now I have no issues with iOS project in the simulator or on my phone.

Sign In or Register to comment.