Skip to content

Instantly share code, notes, and snippets.

@db42
Created December 25, 2017 03:26
Show Gist options
  • Save db42/b40c99060e3a309cfd2402ba45ccfdd1 to your computer and use it in GitHub Desktop.
Save db42/b40c99060e3a309cfd2402ba45ccfdd1 to your computer and use it in GitHub Desktop.
Swift 4 recipes: How to present share options when user takes a screenshot
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(handleScreenshot), name: Notification.Name.UIApplicationUserDidTakeScreenshot, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationUserDidTakeScreenshot, object: nil)
}
@objc func handleScreenshot() {
//use any local image or fetch from a url
let image = try! UIImage(data: Data(contentsOf: URL(string: "https://www.google.co.in/logos/doodles/2017/mohammed-rafis-93th-birthday-5885879699636224.2-l.png")!))
let urlString = "https://www.google.com/any-link-to-share"
let activityVC = UIActivityViewController(activityItems: [urlString, image], applicationActivities: nil)
present(activityVC, animated: true, completion: nil)
//this is required for iPad since activityVC defaults to popover presentation
if let popOver = activityVC.popoverPresentationController {
popOver.sourceView = self.view
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment