iosswiftfacebookfacebook-share

How share a screenshot to Facebook using Swift?


I need to have a Facebook share button on one of my app's view controllers so that when the user pushes it, it will share a screenshot of the user's current screen to Facebook.

I have been watching a few tutorials such as this one on how to implement a Facebook share button: https://www.youtube.com/watch?v=774_-cTjnVM

But these only show how I can share a message on Facebook, and I'm still a little bit confused how to share the whole screen that user is currently interacting with.


Solution

  • Sharing directly to Facebook isn't hard to do. First, import the Social framework:

    import Social
    

    Now add this as the action for your button:

    let screen = UIScreen.mainScreen()
    
    if let window = UIApplication.sharedApplication().keyWindow {
        UIGraphicsBeginImageContextWithOptions(screen.bounds.size, false, 0);
        window.drawViewHierarchyInRect(window.bounds, afterScreenUpdates: false)
        let image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        let composeSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
        composeSheet.setInitialText("Hello, Facebook!")
        composeSheet.addImage(image)
    
        presentViewController(composeSheet, animated: true, completion: nil)
    }
    

    You might be interested to know that UIActivityViewController lets users share to Facebook but also other services. The code above is for your exact question: sharing to Facebook. This code renders the entire visible screen; you can also have individual views render themselves if you want.

    Note: As Duncan C points out in a comment below, this rendering code won't include anything outside your app, such as other apps or system controls.