General Middleware

Add a Share Button in your IOS App in Swift Xcode

When you want to share a media to other apps on the device, you need to use the UIActivityViewController Class. Follow the below steps to share any text or media with other apps:

  1. In Main.storyboard, create an UIImageView, and assign an image from its properties
  2. Create a Share button and link it to an IBAction in the ViewController
  3. Below is the code that can be used to share the image to other apps
//The imageView is the IBOutlet that is linked to the UIImageView in the //Main.storyboard        
       let uiActivityIndicator = UIActivityViewController(activityItems: [
            imageView.image
        ], applicationActivities: nil)
        
        
        present(uiActivityIndicator, animated: true) {
            print("Do something here .... if required")
        }

4. In case you want to share text, use the below code

        let uiActivityIndicator = UIActivityViewController(activityItems: [
            "This is a text message to be shared"
        ], applicationActivities: nil)
        
        present(uiActivityIndicator, animated: true) {
            print("Do something here .... if required")
        }

5. To share video, use the below code

        let uiActivityIndicator = UIActivityViewController(activityItems: [
            NSURL(string: "<local path to the video>") as Any
        ], applicationActivities: nil)
        
        present(uiActivityIndicator, animated: true) {
            print("Do something here .... if required")
        }

Note : The expected object in the activityItems array is of type Any. Hence you can share any type of objects, and depending on its type, the ShareSheet will populate only those apps, that can consume the input object type.

Leave a Reply

Your email address will not be published. Required fields are marked *