Search code examples
iosxamarinxamarin.iosios-camera

SaveToAlbum function is not working in my Xamarin iOS app


Hey guys I am working on a iOS app using Xamarin that open's the camera and takes a picture and then saves it to the camera roll, however when I hit the use photo button the app crashes

here's what VS2012 says is causing the crash:

Unhandled Exception:

System.NullReferenceException: Object reference not set to an instance of an object

Here's my code:

using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;

namespace ToolBelt.iOS
{
    partial class CameraView : UIViewController

    {
        public CameraView (IntPtr handle) : base (handle)
        {       
        }



        public override void DidReceiveMemoryWarning ()
        {
            // Releases the view if it doesn't have a superview.
            base.DidReceiveMemoryWarning ();

            // Release any cached data, images, etc that aren't in use.
        }

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();


            //UIPopoverController popover = new UIPopoverController (ctrl);

            // Perform any additional setup after loading the view, typically from a nib.
        }




        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            if (imageView.Image == null)
            {
                UIImagePickerController picker = new UIImagePickerController();

                picker.SourceType = UIImagePickerControllerSourceType.Camera;
                picker.Delegate = this;
                PresentViewController(picker, true, null);
            }
        }

        [Export("imagePickerController:didFinishPickingImage:editingInfo:")]
        public void FinishedPickingImage(UIKit.UIImagePickerController picker, UIKit.UIImage image, Foundation.NSDictionary editingInfo)
        {
            var someImage = UIImage.FromFile("someImage.jpg");
            someImage.SaveToPhotosAlbum((pic, error) =>
                {
                    var o = pic as UIImage;
                    Console.WriteLine("error:" + error);
                });
            DismissViewController(true, null);

        }
    }


}

what am I doing wrong?

any help would be amazing

Thanks in advance!


Solution

  • You're trying to use a hardcoded image which doesn't exist instead of using the user's picked image.

    Change your code to this:

        [Export("imagePickerController:didFinishPickingImage:editingInfo:")]
        public void FinishedPickingImage(UIKit.UIImagePickerController picker, UIKit.UIImage image, Foundation.NSDictionary editingInfo)
        {
            image.SaveToPhotosAlbum((pic, error) =>
                {
                    Console.WriteLine("error:" + error);
                });
            DismissViewController(true, null);
    
        }