Как отправить трансляцию или уведомление из модели представления .NET Standard 2.0? - PullRequest
0 голосов
/ 20 февраля 2019

У меня есть модель представления, в которой несколько API, поддерживающих разбиение на страницы, называются отдельными задачами.Модель представления находится в модуле .NET Standard 2.0, который используется проектами Xamarin.Android и Xamarin.iOS.Всякий раз, когда я получаю ответ от любого API, мне нужно отправить широковещательную рассылку, если это Xamarin.Android или уведомление, если он вызывается в проекте iOS.Соответствующие экраны будут зарегистрированы для уведомления / трансляции, поэтому при получении их обновленные данные будут извлекаться из БД, а пользовательский интерфейс будет обновляться / дополняться новыми данными.

public class SyncViewModel : BaseViewModel
    {
        private int _totalProductPages = 1;
        private int _totalCategoryPages = 1;
        private int _totalInstProductPages = 1;
        private int _totalUserAssignmentPages = 1;
        private readonly int _pageSize = 25;
        private SyncCommand _command;
        private JsonSerializerSettings _settings;

        public override void Execute(ICommands commands)
        {
            _command = (SyncCommand)commands;
            _settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore
            };

            FetchCategories();
            FetchProducts();
            FetchInstitutionSubscriptionProducts();
        }

        private void FetchProducts()
        {
            Task.Run(async () =>
            {
                ResponseType responseType = ResponseType.PRODUCTS;
                int pageNumber = 1;
                string updatedTime = DBService.GetDB().FetchSyncTime(responseType);
                APIResponseStatus status = APIResponseStatus.ERROR;
                while (pageNumber <= _totalProductPages)
                {
                    Response response = await CloudService.GetCloud().FetchAllProducts(pageNumber, _pageSize, updatedTime);
                    status = ProcessResponse(response, responseType);
                    pageNumber++;
                    //Send notification/broadcast here
                }
                if (status == APIResponseStatus.SUCCESS)
                    DBService.GetDB().InsertOrUpdateSyncTime(responseType);
            });
        }

        private void FetchCategories()
        {
            Task.Run(async () =>
            {
                ResponseType responseType = ResponseType.CATEGORIES;
                int pageNumber = 1;
                string updatedTime = DBService.GetDB().FetchSyncTime(responseType);
                APIResponseStatus status = APIResponseStatus.ERROR;
                while(pageNumber <= _totalCategoryPages)
                {
                    Response response = await CloudService.GetCloud().FetchAllCategories(pageNumber, _pageSize, updatedTime);
                    status = ProcessResponse(response, responseType);
                    pageNumber++;
                    //Send notification/broadcast here
                }
                if (status == APIResponseStatus.SUCCESS)
                    DBService.GetDB().InsertOrUpdateSyncTime(responseType);
            });
        }

        private void FetchInstitutionSubscriptionProducts()
        {
            if (!App.isLoggedIn)
                return;
            Task.Run(async () =>
            {
                ResponseType responseType = ResponseType.INSTITUTION_PRODUCTS;
                int pageNumber = 1;
                string updatedTime = DBService.GetDB().FetchSyncTime(responseType);
                APIResponseStatus status = APIResponseStatus.ERROR;
                while (pageNumber <= _totalInstProductPages)
                {
                    Response response = await CloudService.GetCloud().FetchInstitutionSubscriptionProducts(pageNumber, _pageSize, updatedTime);
                    status = ProcessResponse(response, responseType);
                    pageNumber++;
                    //Send notification/broadcast here
                }
                if (status == APIResponseStatus.SUCCESS)
                    DBService.GetDB().InsertOrUpdateSyncTime(responseType);
            });
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public APIResponseStatus ProcessResponse(Response response, ResponseType type)
        {
            string data = "";
            if (response.status == "error")
            {
                Error error = JsonConvert.DeserializeObject<Error>(response.data);
                data = error.Message;
                return APIResponseStatus.ERROR;
            }
            else if (response.status == "internalError")
            {
                data = response.data;
                return APIResponseStatus.INTERNAL_ERROR;
            }
            else
            {
                data = response.data;
                Pagination paginationDetails = JsonConvert.DeserializeObject<Pagination>(JObject.Parse(data)["_pagination"].ToString(), _settings);
                Console.WriteLine("\n");
                Console.WriteLine("SYNC_RESPONSE_LOG");
                Console.WriteLine("Response Type: " + type.ToString());
                Console.WriteLine("Pagination Details: " + paginationDetails);
                Console.WriteLine("\n");
                switch (type)
                {
                    case ResponseType.PRODUCTS:

                        List<Product> products = JsonConvert.DeserializeObject<List<Product>>(JObject.Parse(data)["products"].ToString(), _settings);
                        DBService.GetDB().InsertOrUpdateProducts(products);
                        if(paginationDetails != null)
                            _totalProductPages = paginationDetails.TotalPages;
                        break;                    
                    case ResponseType.CATEGORIES:
                        SubCategoryList subCategoryList = JsonConvert.DeserializeObject<SubCategoryList>(data, _settings);
                        List<Category> category = subCategoryList.Categories.ToList();
                        DBService.GetDB().InsertOrUpdateCategories(category);
                        if (paginationDetails != null)
                            _totalCategoryPages = paginationDetails.TotalPages;
                        break;
                    case ResponseType.INSTITUTION_PRODUCTS:
                        List<Product> instProducts = JsonConvert.DeserializeObject<List<Product>>(JObject.Parse(data)["products"].ToString(), _settings);
                        DBService.GetDB().InsertOrUpdateProducts(instProducts);
                        if (paginationDetails != null)
                            _totalInstProductPages = paginationDetails.TotalPages;
                        break;
                }
                return APIResponseStatus.SUCCESS;
            }
        }
    }

1 Ответ

0 голосов
/ 21 февраля 2019

Как отправить уведомление на родной платформе iOS и Android

Вы можете реализовать его с помощью DependencyService

в формах,Создание интерфейса

public interface ISendNotifi
{
   void SendNotifi(string content);  //you can set the params as you want
}

Реализация iOS

[assembly: Dependency(typeof(SendNotifiImplementation))]
namespace xxx.iOS
{
  public class SendNotifiImplementation: ISendNotifi
  {
    public SendNotifiImplementation() { }

    void SendNotifi(string content)
    {
        // send notification
    }
  }
}

Реализация Android

[assembly: Dependency(typeof(SendNotifiImplementation))]
namespace xxx.Droid
{
  public class SendNotifiImplementation: ISendNotifi
  {
    public SendNotifiImplementation(Context context):base(context) { }

    void SendNotifi(string content)
    {
        // send notification
    }
  }
}

Донне забывайте сначала зарегистрироваться в службе push-уведомлений Apple и Android.И вы можете вызвать метод в viewmodel и реализовать его на платформе iOS и Android. Например,

...
while (pageNumber <= _totalInstProductPages)
{
   Response response = await CloudService.GetCloud().FetchInstitutionSubscriptionProducts(pageNumber, _pageSize, updatedTime);
   status = ProcessResponse(response, responseType);
   pageNumber++;

   //Send notification/broadcast here
   DependencyService.Get<ISendNotifi>().SendNotifi("pageNumber++");
}
...
...