0

I have a view model where multiple APIs that support pagination are called as separate Tasks. The view model reside in a .NET Standard 2.0 module which is shared by Xamarin.Android and Xamarin.iOS projects. Whenever I receive a response from any API, I need to send a broadcast if it is Xamarin.Android or notification if it is being called within the iOS project. Corresponding screens will have registered for notification/broadcast so that on receiving them updated data will be fetched from DB and UI will be updated/appended with new data.

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;
            }
        }
    }
4
  • Did you want send notification in native iOS and Android platform? Feb 21, 2019 at 5:55
  • @LucasZhang-MSFT yes Xamarin native (Xamarin.Android and Xamarin.iOS) Feb 21, 2019 at 6:20
  • Hey,did you try it? Feb 21, 2019 at 7:57
  • What are you trying to achieve? as its not clear. Are you wanting an actual Local Notification in the status bar or do you want to 'notify' your UI that something has changed so it can react? Feb 26, 2019 at 17:33

1 Answer 1

0

How to send notification in native iOS and Android platform

You can implement it by using DependencyService

in Forms , Creating the Interface

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

iOS Implementation

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

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

Android Implementation

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

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

Don't forgrt to register with the Apple and Android Push Notification Service first. And you can call the method in viewmodel and implement it in iOS and Android platform.Such as

...
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++");
}
...
5
  • In my solution there is no Forms module, there is one Xamarin.Android and Xamarin.iOS module, both shares a .NetStandard 2.0 module for API calls. Does this Dependency service work in this scenario as well? Feb 21, 2019 at 6:46
  • Can you share your sample? Feb 21, 2019 at 6:55
  • sample? My visual studio solution contains a Xamarin.Android and a Xamarin.iOS projects and a .Net Standard Libray project which is shared by both projects. And the specified SyncViewModel resides in the library project. The same library is shared by both the projects. Hence when I run the project say if its androdi it should send broadcast or notification if its an ios one. Does this help? Feb 24, 2019 at 8:29
  • 1
    DI is a pattern that can be used on any framework/language that supports classes and interfaces. XF comes with its own baked in DI service, .Net does not. So you have two choices, use a 3rd party DI container such as TinyIoC, or roll out your own. (DI is just polymorphism where the implementation class is 'injected' into the 'parent' class or interface from the source. Its pretty easy to roll out a simple one yourself, however why do it when there are supported 3rd part libraries out there that add a bunchy of syntatci candy and real fucntionailty to t) Feb 26, 2019 at 17:19
  • TinyIoC (github.com/grumpydev/TinyIoC) if you want to add support for the MVVM pattern with data binding try something like MMVMLight (mvvmlight.net) Feb 26, 2019 at 17:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.