Search code examples
iosswiftscreenshot

Get screenshot of current screen in iOS/swift for sharing


I would like to enable a feature on my phone that allows users to click share, and then they would be able to text their friends a message that by default included a picture of the app (right before the user hit share). I cannot figure out how to do this - and whenever I search on how to do it all I get are tutorials/answers on how to share images in the phone's photo library or by their camera. Any idea on how to do this!


Solution

  • // to create an image from screenshot

    UIGraphicsBeginImageContext(view.frame.size)
    view.layer.renderInContext(UIGraphicsGetCurrentContext())
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    

    // to share the image

    var imagesToShare = [AnyObject]()
    imagesToShare.append(image)
    
    let activityViewController = UIActivityViewController(activityItems: imagesToShare , applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
    presentViewController(activityViewController, animated: true, completion: nil)