HttpClient request crashes on a Xamarin Notification Service Extensions iOS

190 Views Asked by At

I'm trying to request some data from an API using HttpClient in DidReceiveNotificationRequest method (Xamarin iOS Notification Service Extensions project).

When the GetAsync (HttpClient) the extension just crashes.

Am I doing something wrong?

public override async void DidReceiveNotificationRequest(UNNotificationRequest request, Action<UNNotificationContent> contentHandler)
{
    ...

    using (HttpClient client = new HttpClient())
    {
        await client.GetAsync("https://google.com").ConfigureAwait(false); // crashes here
    }

    ...
}

I also tried to use a NSUrlSessionHandler as the HttpClient handler, but no success.

1

There are 1 best solutions below

1
Denys Tsurkanovski On

try use with Uri:

Uri uri = new Uri(string.Format(client.BaseAddress + resource, string.Empty));
HttpResponseMessage responseMessage = await client.GetAsync(uri);

and for iOS need add to .plist - NSLocalNetworkUsageDescription

maybe need add HttpMessageHandler:

 client = new HttpClient(CreateClientHandler()) { BaseAddress = new Uri($"https://{Address}:5001") };
....

private HttpClientHandler CreateClientHandler()
    {
       return new HttpClientHandler
       {
           ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; }
       };
    }