Mapbox V3 bricking non mobile builds, MapboxContext looks like the culprit

Abierto
#2,000 3 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
38/100
Tipo de issue
Error
Claridad
Necesita aclaración
Estado de actividad
Activo
Stack tecnológico
csharp, unity

Línea de trabajo

Start with the MapboxContext entry points named in the issue, especially Initialize(), GetSkuToken(), LoadAndParseConfig(), and LoadConfigurationCoroutine(). Reproduce both the non-mobile server build failure and the iOS loading-screen failure, then inspect the platform directives and configuration flow. Done means Mapbox V3 supports the server build while maps and geolocation still load on iOS.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

So I have been building a game with both a multiplayer component and an online multiplayer component.

I have a server build that I have to create and as is it would refuse to build for non mobile builds with Mapbox V3 installed.

It points to the following methods in MapboxContext when building:

Initialize()

GetSkuToken()

LoadAndParseConfig()

HandleTokenResponse(MapboxConfiguration config, MapboxToken response)

LoadConfigurationCoroutine(bool validateToken = true)

So I had a bright idea, why don't I use a #if with the relevant platforms that use it and turn it off these method with the platforms that don't.

So I went through the script and used the #if for each platform.

This is the modified MapboxContext script:


using System;
using System.Collections;
using System.IO;
using Mapbox.BaseModule;
using Mapbox.BaseModule.Telemetry;
using Mapbox.BaseModule.Utilities;
using UnityEngine;

namespace Mapbox.BaseModule.Map
{
    public class MapboxContext : IMapboxContext
    {
        public MapboxConfiguration Configuration;
        private ITelemetryLibrary _telemetryLibrary;

        private MapboxToken _mapboxToken;
        private string _tokenNotSetErrorMessage = "No configuration file found! Configure your access token from the Mapbox > Setup menu.";

        public MapboxContext()
        {
        }

        public IEnumerator Initialize()
        {
#if UNITY_ANDROID
     yield return LoadConfigurationCoroutine();
#elif Unity_IOS
     yield return LoadConfigurationCoroutine();
#elif UNITY_EDITOR
     yield return LoadConfigurationCoroutine();
#else

#endif
            yield return null;


        }

        public string GetAccessToken()
        {
            return Configuration.AccessToken;
        }

        public string GetSkuToken()
        {
#if UNITY_ANDROID
   return Configuration.GetMapsSkuToken();
#elif Unity_IOS

   return Configuration.GetMapsSkuToken();
  //Debug.LogError("this is apple");
#elif UNITY_EDITOR
            return Configuration.GetMapsSkuToken();
#endif
            return "bums";
        }

        public MapboxTokenStatus TokenStatus()
        {
            if (_mapboxToken == null)
                return MapboxTokenStatus.StatusNotYetSet;
            
            return _mapboxToken.Status;
        }
        
        private MapboxConfiguration LoadAndParseConfig()
        {
#if UNITY_ANDROID
            TextAsset configurationTextAsset = Resources.Load<TextAsset>(Constants.Path.MAPBOX_RESOURCES_RELATIVE);
            if (null == configurationTextAsset)
            {
                Debug.LogError("Need Mapbox Access Token");
                throw new Exception();
            }

            var config = JsonUtility.FromJson<MapboxConfiguration>(configurationTextAsset.text);
            config.Initialize();
            return config;
#elif Unity_IOS

              TextAsset configurationTextAsset = Resources.Load<TextAsset>(Constants.Path.MAPBOX_RESOURCES_RELATIVE);
            if (null == configurationTextAsset)
            {
                Debug.LogError("Need Mapbox Access Token");
                throw new Exception();
            }

            var config = JsonUtility.FromJson<MapboxConfiguration>(configurationTextAsset.text);
            config.Initialize();
            return config;
#elif UNITY_EDITOR
                       TextAsset configurationTextAsset = Resources.Load<TextAsset>(Constants.Path.MAPBOX_RESOURCES_RELATIVE);
            if (null == configurationTextAsset)
            {
                Debug.LogError("Need Mapbox Access Token");
                throw new Exception();
            }

            var config = JsonUtility.FromJson<MapboxConfiguration>(configurationTextAsset.text);
            config.Initialize();
            return config;
#endif

            return null;
        }

        private void HandleTokenResponse(MapboxConfiguration config, MapboxToken response)
        {
#if UNITY_ANDROID
  
            _mapboxToken = response;
            Configuration = config;
            if (_mapboxToken.Status != MapboxTokenStatus.TokenValid)
            {
                config.AccessToken = string.Empty;
                Debug.LogError("Invalid Token");
            }
            else
            {
                ConfigureTelemetry();
            }
#elif Unity_IOS

            _mapboxToken = response;
            Configuration = config;
            if (_mapboxToken.Status != MapboxTokenStatus.TokenValid)
            {
                config.AccessToken = string.Empty;
                Debug.LogError("Invalid Token");
            }
            else
            {
                ConfigureTelemetry();
            }
#elif UNITY_EDITOR
    
            _mapboxToken = response;
            Configuration = config;
            if (_mapboxToken.Status != MapboxTokenStatus.TokenValid)
            {
                config.AccessToken = string.Empty;
                Debug.LogError("Invalid Token");
            }
            else
            {
                ConfigureTelemetry();
            }
#endif

        }

        private const float TokenValidationTimeoutSeconds = 10f;

        public IEnumerator LoadConfigurationCoroutine(bool validateToken = true)
        {
#if UNITY_ANDROID
     var config = LoadAndParseConfig();

            if (validateToken)
            {
                var tokenValidator = new MapboxTokenApi();
                var configLoaded = false;
                tokenValidator.Retrieve(config.GetMapsSkuToken, config.AccessToken, (response) =>
                {
                    HandleTokenResponse(config, response);
                    configLoaded = true;
                });

                var elapsed = 0f;
                while (!configLoaded)
                {
                    elapsed += Time.deltaTime;
                    if (elapsed >= TokenValidationTimeoutSeconds)
                    {
                        Debug.LogError("Token validation timed out. Proceeding with unvalidated configuration.");
                        Configuration = config;
                        break;
                    }

                    yield return null;
                }
            }
            else
            {
                Configuration = config;
            }
#elif Unity_IOS

     var config = LoadAndParseConfig();

            if (validateToken)
            {
                var tokenValidator = new MapboxTokenApi();
                var configLoaded = false;
                tokenValidator.Retrieve(config.GetMapsSkuToken, config.AccessToken, (response) =>
                {
                    HandleTokenResponse(config, response);
                    configLoaded = true;
                });

                var elapsed = 0f;
                while (!configLoaded)
                {
                    elapsed += Time.deltaTime;
                    if (elapsed >= TokenValidationTimeoutSeconds)
                    {
                        Debug.LogError("Token validation timed out. Proceeding with unvalidated configuration.");
                        Configuration = config;
                        break;
                    }

                    yield return null;
                }
            }
            else
            {
                Configuration = config;
            }
#elif UNITY_EDITOR
            var config = LoadAndParseConfig();

            if (validateToken)
            {
                var tokenValidator = new MapboxTokenApi();
                var configLoaded = false;
                tokenValidator.Retrieve(config.GetMapsSkuToken, config.AccessToken, (response) =>
                {
                    HandleTokenResponse(config, response);
                    configLoaded = true;
                });

                var elapsed = 0f;
                while (!configLoaded)
                {
                    elapsed += Time.deltaTime;
                    if (elapsed >= TokenValidationTimeoutSeconds)
                    {
                        Debug.LogError("Token validation timed out. Proceeding with unvalidated configuration.");
                        Configuration = config;
                        break;
                    }

                    yield return null;
                }
            }
            else
            {
                Configuration = config;
            }
#endif
            yield return null;
        }

        private void ConfigureTelemetry()
        {
            //TODO: enable after token validation has been made async
            if (
            	null == Configuration ||
                string.IsNullOrEmpty(Configuration.AccessToken) ||
                _mapboxToken.Status != MapboxTokenStatus.TokenValid
            )
            {
            	Debug.LogError(_tokenNotSetErrorMessage);
            	return;
            }
            try
            {
                _telemetryLibrary = TelemetryFactory.GetTelemetryInstance();
                _telemetryLibrary.Initialize(Configuration.AccessToken);
                _telemetryLibrary.SetLocationCollectionState(Configuration.TelemetryEnabled);
                _telemetryLibrary.SendTurnstile();
                _telemetryLibrary.SendSdkEvent();
            }
            catch (Exception ex)
            {
                Debug.LogErrorFormat("Error initializing telemetry: {0}", ex);
            }
        }

        public void ValidateToken(Action callback = null)
        {
            var tokenValidator = new MapboxTokenApi();
            tokenValidator.Retrieve(GetSkuToken, GetAccessToken(), (response) =>
            {
                _mapboxToken = response;
                if (_mapboxToken.Status != MapboxTokenStatus.TokenValid)
                {
                    Debug.LogError("Invalid Token");
                }
                callback?.Invoke();
            });
        }

        public bool GetTelemetryCollectiongState()
        {
            return Configuration.TelemetryEnabled;
        }
        
        public bool SetTelemetryCollectionState(bool state)
        {
            Configuration.TelemetryEnabled = state;
            _telemetryLibrary.SetLocationCollectionState(Configuration.TelemetryEnabled);

            try
            {
                var configurationFilePath = Constants.Path.MAPBOX_CONFIG_ABSOLUTE;
                var json = JsonUtility.ToJson(Configuration);
                File.WriteAllText(configurationFilePath, json);
                Debug.Log("Successfully set telemetry collection state to " + state);
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return false;
            }
        }
    }

    public interface IMapboxContext
    {
        public string GetAccessToken();
        public string GetSkuToken();
    }
}

And it worked, I could make a server build now, but there is a side effect: when I switched to make an IOS build and got it on my phone, it refused to make a map and got stuck on the loading screen.

I dunno why geo-location is not working on that IOS build, it should be running anything with #if Unity_IOS which runs the script as it was before.

I cannot use Mapbox V3 without having both a server build and a geo location feature so this is very important to me.

I use to use a Unity Asset Store package called Go Map that could add a geo location feature without any effect on other builds, but I would prefer Mapbox V3 because GoMaps bills on the amount of Vector Tiles used while Mapbox to bill me per user.

I bring this up because I want Mapbox V3 to overcome this hurdle and use it instead of GoMaps so what I am trying to suggest is if you guys could look into GoMaps and see what they are doing that avoids these issues and what you guys could learn from them.

This is the Unity Asset Store page:
https://assetstore.unity.com/packages/tools/integration/go-map-3d-map-for-ar-gaming-68889

My best case scenario is that Mapbox V3 figures out a solution, but if nothing changes I have to use Maps Go instead to keep my essential features.

Double posted this on the discord to make sure its heard.

Lenguaje dominante
C#
Estrellas
787
Forks
228
Métricas de merge de PR
Sin PR fusionados en 30 d

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de mapbox/mapbox-unity-sdk

Todos los issues de mapbox/mapbox-unity-sdk

Issues similares

Más issues de C#

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.