Last active
June 6, 2021 08:58
-
-
Save benjaminmayo/629a9a223043ef0e80701a81cf38b6f9 to your computer and use it in GitHub Desktop.
Working example of UIActivityItemProvider customising a shared URL depending on the activity type. http://benjaminmayo.co.uk/twitter-app-sharing-link-garbage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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