Skip to content

Commit ac8a592

Browse files
Map doesn't re-render If there is no internet (#2512)
* Map doesn't re-render If there is no internet * Fix build * Fix Map Permission Denied * Refactor code analysis attributes in MapHandler Removed `RequiresDynamicCode` and `RequiresUnreferencedCode` attributes from `CreatePlatformView` and `DisconnectHandler` methods. Replaced them with `UnconditionalSuppressMessage` attributes to suppress related warnings. Updated `ConnectHandler` to include new suppress messages while preserving functionality. These changes improve code analysis compliance without altering method behavior.
1 parent 9233b73 commit ac8a592

File tree

3 files changed

+65
-40
lines changed

3 files changed

+65
-40
lines changed

src/CommunityToolkit.Maui.Maps/AppBuilderExtensions.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,6 @@ public static class AppBuilderExtensions
4444
/// </code>
4545
/// </example>
4646
///
47-
[RequiresDynamicCode("Calls System.Text.Json.JsonSerializer.Deserialize<TValue>(String, JsonSerializerOptions)")]
48-
[RequiresUnreferencedCode("Calls System.Text.Json.JsonSerializer.Deserialize<TValue>(String, JsonSerializerOptions)")]
4947
public static MauiAppBuilder UseMauiCommunityToolkitMaps(this MauiAppBuilder builder, string key)
5048
{
5149
builder.ConfigureMauiHandlers(handlers =>

src/CommunityToolkit.Maui.Maps/Handler/Map/MapHandler.Windows.cs

Lines changed: 53 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
using System.Diagnostics.CodeAnalysis;
2-
using System.Globalization;
1+
using System.Globalization;
32
using System.Text.Json;
43
using Microsoft.Maui.Controls.Maps;
54
using Microsoft.Maui.Handlers;
@@ -15,17 +14,10 @@
1514
namespace CommunityToolkit.Maui.Maps.Handlers;
1615

1716
/// <inheritdoc />
18-
[RequiresDynamicCode("Calls System.Text.Json.JsonSerializer.Deserialize<TValue>(String, JsonSerializerOptions)")]
19-
[RequiresUnreferencedCode("Calls System.Text.Json.JsonSerializer.Deserialize<TValue>(String, JsonSerializerOptions)")]
2017
public partial class MapHandlerWindows : MapHandler
2118
{
2219
MapSpan? regionToGo;
2320

24-
readonly JsonSerializerOptions jsonSerializerOptions = new()
25-
{
26-
PropertyNameCaseInsensitive = true
27-
};
28-
2921
/// <summary>
3022
/// Initializes a new instance of the <see cref="MapHandlerWindows"/> class.
3123
/// </summary>
@@ -42,41 +34,43 @@ public MapHandlerWindows() : base(Mapper, CommandMapper)
4234
}
4335

4436
internal static string? MapsKey { get; set; }
37+
internal static string? MapPage { get; private set; }
4538

4639
/// <inheritdoc/>
47-
[RequiresDynamicCode("Calls System.Text.Json.JsonSerializer.Deserialize<TValue>(String, JsonSerializerOptions)")]
48-
[RequiresUnreferencedCode("Calls System.Text.Json.JsonSerializer.Deserialize<TValue>(String, JsonSerializerOptions)")]
49-
#pragma warning disable IL2046 // 'RequiresUnreferencedCodeAttribute' annotations must match across all interface implementations or overrides.
50-
#pragma warning disable IL3051 // 'RequiresDynamicCodeAttribute' annotations must match across all interface implementations or overrides.
5140
protected override FrameworkElement CreatePlatformView()
52-
#pragma warning restore IL3051 // 'RequiresDynamicCodeAttribute' annotations must match across all interface implementations or overrides.
53-
#pragma warning restore IL2046 // 'RequiresUnreferencedCodeAttribute' annotations must match across all interface implementations or overrides.
5441
{
5542
if (string.IsNullOrEmpty(MapsKey))
5643
{
5744
throw new InvalidOperationException("You need to specify a Bing Maps Key");
5845
}
5946

60-
var mapPage = GetMapHtmlPage(MapsKey);
47+
MapPage = GetMapHtmlPage(MapsKey);
6148
var webView = new MauiWebView(new WebViewHandler());
62-
webView.NavigationCompleted += HandleWebViewNavigationCompleted;
63-
webView.WebMessageReceived += WebViewWebMessageReceived;
64-
webView.LoadHtml(mapPage, null);
6549

6650
return webView;
6751
}
6852

6953
/// <inheritdoc />
70-
[RequiresDynamicCode("Calls System.Text.Json.JsonSerializer.Deserialize<TValue>(String, JsonSerializerOptions)")]
71-
[RequiresUnreferencedCode("Calls System.Text.Json.JsonSerializer.Deserialize<TValue>(String, JsonSerializerOptions)")]
72-
#pragma warning disable IL2046 // 'RequiresUnreferencedCodeAttribute' annotations must match across all interface implementations or overrides.
73-
#pragma warning disable IL3051 // 'RequiresDynamicCodeAttribute' annotations must match across all interface implementations or overrides.
54+
protected override void ConnectHandler(FrameworkElement platformView)
55+
{
56+
if (platformView is MauiWebView mauiWebView)
57+
{
58+
LoadMap(platformView);
59+
60+
mauiWebView.NavigationCompleted += HandleWebViewNavigationCompleted;
61+
mauiWebView.WebMessageReceived += WebViewWebMessageReceived;
62+
Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
63+
}
64+
65+
base.ConnectHandler(platformView);
66+
}
67+
68+
/// <inheritdoc />
7469
protected override void DisconnectHandler(FrameworkElement platformView)
75-
#pragma warning restore IL3051 // 'RequiresDynamicCodeAttribute' annotations must match across all interface implementations or overrides.
76-
#pragma warning restore IL2046 // 'RequiresUnreferencedCodeAttribute' annotations must match across all interface implementations or overrides.
7770
{
78-
if (PlatformView is MauiWebView mauiWebView)
71+
if (platformView is MauiWebView mauiWebView)
7972
{
73+
Connectivity.ConnectivityChanged -= Connectivity_ConnectivityChanged;
8074
mauiWebView.NavigationCompleted -= HandleWebViewNavigationCompleted;
8175
mauiWebView.WebMessageReceived -= WebViewWebMessageReceived;
8276
}
@@ -415,9 +409,21 @@ function hideInfoWindow()
415409

416410
static async Task<Location?> GetCurrentLocation()
417411
{
418-
var geoLocator = new Geolocator();
419-
var position = await geoLocator.GetGeopositionAsync();
420-
return new Location(position.Coordinate.Latitude, position.Coordinate.Longitude);
412+
if (await Geolocator.RequestAccessAsync() != GeolocationAccessStatus.Allowed)
413+
{
414+
return null;
415+
}
416+
417+
try
418+
{
419+
var geoLocator = new Geolocator();
420+
var position = await geoLocator.GetGeopositionAsync();
421+
return new Location(position.Coordinate.Latitude, position.Coordinate.Longitude);
422+
}
423+
catch
424+
{
425+
return null;
426+
}
421427
}
422428

423429
async void HandleWebViewNavigationCompleted(WebView2 sender, CoreWebView2NavigationCompletedEventArgs args)
@@ -431,8 +437,6 @@ async void HandleWebViewNavigationCompleted(WebView2 sender, CoreWebView2Navigat
431437
}
432438
}
433439

434-
[RequiresDynamicCode("Calls System.Text.Json.JsonSerializer.Deserialize<TValue>(String, JsonSerializerOptions)")]
435-
[RequiresUnreferencedCode("Calls System.Text.Json.JsonSerializer.Deserialize<TValue>(String, JsonSerializerOptions)")]
436440
async void WebViewWebMessageReceived(WebView2 sender, CoreWebView2WebMessageReceivedEventArgs args)
437441
{
438442
// For some reason the web message is empty
@@ -441,7 +445,7 @@ async void WebViewWebMessageReceived(WebView2 sender, CoreWebView2WebMessageRece
441445
return;
442446
}
443447

444-
var eventMessage = JsonSerializer.Deserialize<EventMessage>(args.WebMessageAsJson, jsonSerializerOptions);
448+
var eventMessage = JsonSerializer.Deserialize<EventMessage>(args.WebMessageAsJson, SerializerContext.Default.EventMessage);
445449

446450
// The web message (or it's ID) could not be deserialized to something we recognize
447451
if (eventMessage is null || !Enum.TryParse<EventIdentifier>(eventMessage.Id, true, out var eventId))
@@ -460,25 +464,23 @@ async void WebViewWebMessageReceived(WebView2 sender, CoreWebView2WebMessageRece
460464
switch (eventId)
461465
{
462466
case EventIdentifier.BoundsChanged:
463-
var mapRect = JsonSerializer.Deserialize<Bounds>(payloadAsString, jsonSerializerOptions);
467+
var mapRect = JsonSerializer.Deserialize<Bounds>(payloadAsString, SerializerContext.Default.Bounds);
464468
if (mapRect?.Center is not null)
465469
{
466470
VirtualView.VisibleRegion = new MapSpan(new Location(mapRect.Center.Latitude, mapRect.Center.Longitude),
467471
mapRect.Height, mapRect.Width);
468472
}
469473
break;
470474
case EventIdentifier.MapClicked:
471-
var clickedLocation = JsonSerializer.Deserialize<Location>(payloadAsString,
472-
jsonSerializerOptions);
475+
var clickedLocation = JsonSerializer.Deserialize<Location>(payloadAsString, SerializerContext.Default.Location);
473476
if (clickedLocation is not null)
474477
{
475478
VirtualView.Clicked(clickedLocation);
476479
}
477480
break;
478481

479482
case EventIdentifier.InfoWindowClicked:
480-
var clickedInfoWindowWebView = JsonSerializer.Deserialize<InfoWindow>(payloadAsString,
481-
jsonSerializerOptions);
483+
var clickedInfoWindowWebView = JsonSerializer.Deserialize<InfoWindow>(payloadAsString, SerializerContext.Default.InfoWindow);
482484
var clickedInfoWindowWebViewId = clickedInfoWindowWebView?.InfoWindowMarkerId;
483485

484486
if (!string.IsNullOrEmpty(clickedInfoWindowWebViewId))
@@ -494,7 +496,7 @@ async void WebViewWebMessageReceived(WebView2 sender, CoreWebView2WebMessageRece
494496
break;
495497

496498
case EventIdentifier.PinClicked:
497-
var clickedPinWebView = JsonSerializer.Deserialize<Pin>(payloadAsString, jsonSerializerOptions);
499+
var clickedPinWebView = JsonSerializer.Deserialize<Pin>(payloadAsString, SerializerContext.Default.Pin);
498500
var clickedPinWebViewId = clickedPinWebView?.MarkerId?.ToString();
499501

500502
if (!string.IsNullOrEmpty(clickedPinWebViewId))
@@ -510,4 +512,17 @@ async void WebViewWebMessageReceived(WebView2 sender, CoreWebView2WebMessageRece
510512
break;
511513
}
512514
}
515+
516+
void Connectivity_ConnectivityChanged(object? sender, ConnectivityChangedEventArgs e)
517+
{
518+
LoadMap(PlatformView);
519+
}
520+
521+
static void LoadMap(FrameworkElement platformView)
522+
{
523+
if (platformView is MauiWebView mauiWebView && Connectivity.NetworkAccess == NetworkAccess.Internet)
524+
{
525+
mauiWebView.LoadHtml(MapPage, null);
526+
}
527+
}
513528
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
using System.Text.Json.Serialization;
2+
using Microsoft.Maui.Controls.Maps;
3+
4+
namespace CommunityToolkit.Maui.Maps.Handlers;
5+
6+
[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true)]
7+
[JsonSerializable(typeof(EventMessage))]
8+
[JsonSerializable(typeof(Pin))]
9+
[JsonSerializable(typeof(Location))]
10+
[JsonSerializable(typeof(Bounds))]
11+
[JsonSerializable(typeof(InfoWindow))]
12+
sealed partial class SerializerContext : JsonSerializerContext;

0 commit comments

Comments
 (0)