问题描述
我试图观察在 Iphone 上使用我的应用程序时是否截取了屏幕截图.如果在使用我的应用程序时截图,我想删除该截图.
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.
我成功地使用了 Observer 方法来检查在使用我的应用程序时是否截取了屏幕截图.
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.
如何立即删除在使用我的 APP 时从 Iphone 上截取的屏幕截图(经用户许可)?我也想知道有没有可能.
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.
推荐答案
试试这个:
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)
}
}
}
这篇关于观察并删除(截图),如果在我的Iphone中使用我的应用程序时截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!