Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DidReceiveMemoryWarning in IOS using Xamarin Forms

How can you catch the DidReceiveMemoryWarning using xamarin forms.

I can see them in the application output when debugging in xamarin studio, but i cant find how to catch the event or how to see how much memory is used.

I tried AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize but it throws a not implemented exception

like image 307
Steve Avatar asked Aug 28 '14 11:08

Steve


2 Answers

There are 3 ways to capture Memory Warnings in iOS (or at least this what I know of :)

These three ways are:

  1. In your ViewControllers, you could override DidReceiveMemoryWarning() and handle the warning there. This is not really the best way for Xamarin.Forms as you do not have UIViewController to override these methods, so move on to options 2 and 3.

  2. In your AppDelegate, override ReceiveMemoryWarning method. This will get fired when the iOS is running low on memory. You could wire this method to any code you have on your PCL code or just handle it in your platform-specific project.

    public override void ReceiveMemoryWarning (UIApplication application)
    {
            // handle low memory warnings here
    }
    
  3. You could use iOS NotificationCentre to receive a notification when there is a memory warning. This could be done like this:

    // Method style void Callback (NSNotification notification) 
    {
            Console.WriteLine ("Received a notification UIApplication", notification);
    }
    
    void Setup () 
    {
            NSNotificationCenter.DefaultCenter.AddObserver (UIApplication.DidReceiveMemoryWarningNotification, Callback); 
    }
    

You could then wire this "CallBack" to your PCL project to free up some memory.

You could also test this on the simulator using

Hardware >> Simulate Memory Warnings

like image 176
Has AlTaiar Avatar answered Nov 06 '22 15:11

Has AlTaiar


You can override DidReceiveMemoryWarning in you iOS project, and from there notify the Xamarin.Forms pages. I can think of many ways to achieve this, but here are the 2 more obvious:

  • use Dependency Injection, and inject the warning as an event. Xamarin.Forms provides DependencyService as a DI container, but you can use the one you want: http://developer.xamarin.com/guides/cross-platform/xamarin-forms/dependency-service/
  • send messages from the native project to the other one, e.g. by using Xamarin.Forms MessagingCenter: http://developer.xamarin.com/guides/cross-platform/xamarin-forms/messaging-center/
like image 31
Stephane Delcroix Avatar answered Nov 06 '22 15:11

Stephane Delcroix