Jake2Finn
Jake2Finn

Reputation: 536

Activity controller for sharing screenshots displays empty

I want my code to share a screenshot when a button named share is clicked.

The button function looks like this:

Swift 3

    func shareBtnAction(_ sender: AnyObject) {

// first I take a screenshot of the drawing    
        UIGraphicsBeginImageContext(drawingAreaView.bounds.size)
        drawingAreaView.image?.draw(in: CGRect(x: 0, y: 0, width: drawingAreaView.frame.size.width, height: drawingAreaView.frame.size.height))

// defining the variable for activityItems  
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

// Initialize and present UIActivityViewController         
        let activity = UIActivityViewController(activityItems: [image], applicationActivities: nil)
        present(activity, animated: true, completion: nil)
    }

The result, however looks like this:

enter image description here

My code works when I replace the image with a text string

    func shareBtnAction(_ sender: AnyObject) {

// defining the variable for activityItems  
        let text = "This is a test"

// Initialize and present UIActivityViewController         
        let activity = UIActivityViewController(activityItems: [text], applicationActivities: nil)
        present(activity, animated: true, completion: nil)
    }

So I guess my code does not recognize the image to be a UIImage. I just cannot figure out why.

Upvotes: 1

Views: 447

Answers (1)

Jake2Finn
Jake2Finn

Reputation: 536

I figured out, swift 3 wants you to initialize UIGraphicsGetImageFromCurrentImageContext more concretely as an UIImage type:

let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!

OR in Swift 4:

let image = UIGraphicsGetImageFromCurrentImageContext() as Any

Upvotes: 3

Related Questions