From UIViewController to screenshot to social media.
You want to implement a share button that takes a screenshot from your app and let’s users share it to social media.
You cant find the complete project on GitHub here.
Let’s get started with a clean project.
Let’s start with a clean project. Add a share button to the default view controller. For the button image, you can choose square.and.arrow.up
to make it look like a native share button.
Add a new view controller which will produce the image to be shared. Do not add a segue from the old view controller to the new one — this will be done programmatically.
Change it’s size to be a custom value in the Size inspector
by selecting Freeform
and entering the size.
Also make sure you uncheck **Resize View From Nib**
in the Attributes inspector.
Else the custom size will not appear when we instantiate the view controllor.
Add a new class for this view controller called ShareViewController
and assign it in the storyboard. Also give it the Storyboard ID: shareVC
.
You can add whatever you want to the view controller.
First, let’s make a simple implementation for the ShareViewController
:
It updates the message field, and provides a simple populate
method for that task (very important if you have non-trivial data types to separate the GUI and logic!).
The most important method is the one that takes the screenshot — without showing the **ShareViewController**
:
UIGraphicsBeginImageContextWithOptions
. Pass the vc.view.frame.size
such that it uses the same size as the ShareViewController
. The 3.0
factor is a scaling factor to increase the quality of the image — you will need to dial this in depending on the size of your ShareViewController
.ShareViewController
with the data.vc.view.layer.render(in: UIGraphicsGetCurrentContext()!)
. This creates the screenshot from the view controller without showing it.UIGraphicsEndImageContext
!Next, in the main ViewController
, hook up a short method to the share button:
Here, share
is implemented as follows:
UIImage
using the take_screen_shot
method.UIActivityViewController
, passing the URL to share.We already did the screen shot method. Next, the save image method:
which should be self-explanatory.
The only missing method is the error message:
This, too, should be self-explanatory.
Let’s see how it turned out — pressing the button gives:
As we can see, there’s a preview of the image we’re sharing. The image is:
Note that not all of the buttons may work correctly. For example, if you choose Save Image
, you may get:
**This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSPhotoLibraryAddUsageDescription key with a string value explaining to the user how the app uses this data.**
So… do that!
You cant find the complete project on GitHub here.
Happy sharing!
Oliver K. Ernst
October 9, 2020