TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Can I define what is being copied when the user presses COPY on a sharesheet?

Forums > SwiftUI

When I use a code like this to present a ShareSheet

import SwiftUI

extension UIApplication {
  static let keyWindow = keyWindowScene?.windows.filter(\.isKeyWindow).first
  static let keyWindowScene = shared.connectedScenes.first { $0.activationState == .foregroundActive } as? UIWindowScene  
}

extension View {

  func shareSheet(isPresented: Binding<Bool>, items: [Any]) -> some View {
    guard isPresented.wrappedValue else { return self }
    let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
    let presentedViewController = UIApplication.keyWindow?.rootViewController?.presentedViewController ?? UIApplication.keyWindow?.rootViewController
    activityViewController.completionWithItemsHandler = { _, _, _, _ in isPresented.wrappedValue = false }
    presentedViewController?.present(activityViewController, animated: true)
    return self
  }

}

struct ContentView: View {

  @State private var isPresentingShareSheet = false

  var body: some View {
    Button("Present Share Sheet") { isPresentingShareSheet = true }
      .shareSheet(isPresented: $isPresentingShareSheet, items: ["Share me!"])
  }

}

A button named COPY is always present on the sharesheet itself.

When I press copy, what exactly is being copied and from where?

If this copy means the text or element that is selected when the sharesheet is triggered this creates me a problem, because I want to pass a rich text that is composed of a title, an image and a long description.

Can I define a function to run when that button is pressed?

3      

Hello,

yes, you can customize this, but not by running a function. Instead you need to create custom "wrapper" around the data you pass to the share sheet that conforms to UIActivityItemSource .

You can then do something like this:

func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
    if activityType == .copyToPasteboard {
        return richText
    } else {
        return standardText
    }
}

Feel free to check more tips about share sheet on my blog - https://nemecek.be/blog/189/wip-sharing-data-with-uiactivityviewcontroller-tips-tricks

3      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.