Observe and delete (screenshot), if a screenshot is taken while using my App in Iphone

Viewed 1922

I am trying to observe if a screenshot is taken while using my App on Iphone. If a screenshot is taken while using my App, I would like that screenshot to be deleted.

I also understand that during deletion, user needs to give permission for deletion.

I used an Observer method successfully to check if a screenshot is taken while using my app.

I am stuck at a point where I need to access that screenshot and delete it, of course with user permission.

```public override void OnActivated(UIApplication application)
    {
        try
        {
            // Start observing screenshot notification
            if (_screenshotNotification == null)
            {
                _screenshotNotification = NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.UserDidTakeScreenshotNotification,
                            (NSNotification n) => {

Console.WriteLine("UserTookScreenshot");                                    

var photosOptions = new PHFetchOptions();                                   

photosOptions.SortDescriptors = new NSSortDescriptor[] { new 

NSSortDescriptor("creationDate", false) };                                  

photosOptions.FetchLimit = 1;                                                                       

var photo = PHAsset.FetchAssets(photosOptions);                                 

Console.WriteLine(photo);                                   

var filePath = photo.Path;                                  

System.IO.File.Delete(filePath);                                    

n.Dispose();
                                       }
                     );
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
        }
    }```

I know the above code does not work with deleting the current screenshot taken while using my App. It gives a general idea on what I want to achieve.

How can I delete the screenshot taken while using my APP from Iphone instantly (with user permission)? I would also like to know if it is possible.

3 Answers

Yes it is possible, you obviously have to properly manage the permissions for the image. In order to do this, first you have to add an observer to detect the screenshot as shown here

First: declare an NSObject variable on your AppDelegate. In the example below I added _screenshotNotification.

Second: On the AppDelegate’s OnActivated (app moving to active state), add code to start observing the UIApplication.UserDidTakeScreenshotNotification and then do something once the notification is posted.

Third: On the AppDelegate’s OnResignActivation (app moving to inactive state), add code to remove the observer.

Then you have to actually find the file & delete, so you in the page you are trying to do it, just add the Foundation & Photos using statements and then try this. (I converted the Swift from here but haven't tested it)

var fetchOptions = new PHFetchOptions();
fetchOptions.SortDescriptors[0] = new Foundation.NSSortDescriptor("creationDate", true);
var fetchResult = PHAsset.FetchAssets(PHAssetMediaType.Image, fetchOptions);
if (fetchResult != null)
{
             var lastAsset = (fetchResult.LastObject as PHAsset);
             var arrayToDelete = new PHAsset[1] { lastAsset };
             PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => { PHAssetChangeRequest.DeleteAssets(arrayToDelete); },
                                                              async (bool success, NSError errorMessage) => { }); //Handle Completion Here Appropriately 
}

I don't think it is possible.

From iOS 11, when you take a screenshot, the snap minimizes itself in the bottom left corner of the screen. From here, save or delete the screenshot is decided by the user.(as the image below)

You can read more information form this article: how-take-screenshot-iphone-or-ipad-ios-11

screenshot

Here comes the problem how do you know whether user has save the screenshot or not?

If the user saved, you can delete the screenShot form the photoLibrary.

While if the user dose not save the screenshot, what your deleted is not the screenshot.

Try this:

func didTakeScreenshot() {
    self.perform(#selector(deleteAppScreenShot), with: nil, afterDelay: 1, inModes: [])
}

@objc func deleteAppScreenShot() {
    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors?[0] = Foundation.NSSortDescriptor(key: "creationDate", ascending: true)
    let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
    guard let lastAsset = fetchResult.lastObject else { return }
    PHPhotoLibrary.shared().performChanges {
        PHAssetChangeRequest.deleteAssets([lastAsset] as NSFastEnumeration)
    } completionHandler: { (success, errorMessage) in
        if !success, let errorMessage = errorMessage {
            print(errorMessage.localizedDescription)
        }
    }
}
Related