Forum Xamarin.iOS

Saving a screen shot in Xamarin iOs,

So I am using a PCL Xamarin forms project.
I am trying to save a screenshot from my mobile device onto the phone.

The code for doing so looks like this:
public async Task CaptureAsync()
{

        byte[] byteResult;
        Device.BeginInvokeOnMainThread(() =>
        {
            var view = UIApplication.SharedApplication.KeyWindow.RootViewController.View;

            UIGraphics.BeginImageContext(view.Frame.Size);
            view.DrawViewHierarchy(view.Frame, true);
            image = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();

            var documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            string jpgFilename = System.IO.Path.Combine(documentsDirectory, "whitchurch.jpg");


            //using (NSData imageData = image.AsPNG())
            //{
            //    Byte[] myByteArray = new Byte[imageData.Length];
            //    System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length));
            //    byteResult = myByteArray;
            //}

            Directory.CreateDirectory(jpgFilename);

            //File.WriteAllBytes(jpgFilename, byteResult);

            NSData imgData = image.AsJPEG();

            NSError err = null;

            if (imgData.Save(jpgFilename, false, out err))
            {
                Console.WriteLine("saved as " + jpgFilename);
            }
            else
            {
                Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
            }



            ////Just for testing, to see if screenshot got written to the photoalbum, could be used in future - Whitchurch 6 / 13 / 2016.
            //image.SaveToPhotosAlbum((img, err) =>
            //   {
            //       if (err != null)
            //           Console.WriteLine("error saving image: {0}", err);
            //       else
            //           Console.WriteLine("image saved to photo album");
            //   });


            //});

        });


            //return byteResult = await Task.Run(async () => await returnImageBytes(image));
     }

I have come to a point where i get an error that says

The file “whitchurch.jpg” couldn’t be saved in the folder “Pictures”."

It looks like a permission issue, Can some one help me with this.

Thanks

Best Answers

Answers

Sign In or Register to comment.