Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Working example of UIActivityItemProvider customising a shared URL depending on the activity type. http://benjaminmayo.co.uk/twitter-app-sharing-link-garbage
import UIKit
class ViewController : UIViewController {
// Monotonous view setup hidden. Imagine there's a button on screen that gets tapped and fires the action below.
@IBAction func shareLinkButtonPressed(_ sender: Any) {
let urlToShare = URL(string: "http://twitter.com/bzamayo")! // the base URL, in a real app this would be provided dynamically based on the current context
let sharingActivityItemProvider = LinkSharingActivityItemProvider(url: urlToShare) // make an activity item provider, defined below
let activityViewController = UIActivityViewController(activityItems: [sharingActivityItemProvider], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
}
public class LinkSharingActivityItemProvider : UIActivityItemProvider {
public let sharingURL: URL
public init(url: URL) {
self.sharingURL = url
super.init(placeholderItem: url)
}
public override var item: Any { // customise the item for the current `activityType`
var components = URLComponents(url: self.sharingURL, resolvingAgainstBaseURL: true)!
if let activityType = self.activityType {
let rawActivityValue = activityType.rawValue
let queryValue = "twcamp^share|twsrc^ios|twgr^\(rawActivityValue)"
let queryItem = URLQueryItem(name: "ref_src", value: queryValue)
components.queryItems = (components.queryItems ?? []) + [queryItem]
}
return components.url!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment