如何从.NET Standard 2.0视图模型发送广播或通知?

问题描述 投票:0回答:1

我有一个视图模型,其中支持分页的多个API被称为单独的任务。视图模型位于.NET Standard 2.0模块中,该模块由Xamarin.Android和Xamarin.iOS项目共享。每当我收到来自任何API的响应时,如果是Xamarin.Android,我需要发送广播,或者如果在iOS项目中调用它,则需要发送通知。相应的屏幕将注册通知/广播,以便在接收它们时将从DB获取更新的数据,并且UI将被更新/附加新数据。

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;
            }
        }
    }
c# xamarin.android xamarin.ios .net-standard-2.0
1个回答
0
投票

如何在本机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
    }
  }
}

不要忘记先注册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++");
}
...
© www.soinside.com 2019 - 2024. All rights reserved.