Created
July 26, 2021 10:39
-
-
Save sindresorhus/9e5f12b4c63c33977e0939ffa2f34983 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
extension UIImage { | |
private final class UIImageActivityItemSource: NSObject, UIActivityItemSource { | |
var image = UIImage() | |
var title: String? | |
var url: URL? | |
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any { | |
UIImage() | |
} | |
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? { | |
image | |
} | |
func activityViewControllerLinkMetadata(_: UIActivityViewController) -> LPLinkMetadata? { | |
let metadata = LPLinkMetadata() | |
if let url = url { | |
metadata.originalURL = url | |
metadata.url = url | |
} | |
if let title = title { | |
metadata.title = title | |
} | |
// This makes it so that the activity controller shows a thumbnail. It wouldn't if you just pass a plain UIImage to it. | |
metadata.imageProvider = NSItemProvider(object: image) | |
return metadata | |
} | |
} | |
/** | |
Makes the image a source for an `UIActivityViewController`. | |
The benefit of using this instead of passing the image directly is that with this one the activity controller shows a thumbnail and you can also set title and URL. | |
*/ | |
func asActivityItemSource( | |
title: String? = nil, | |
url: URL? = nil | |
) -> UIActivityItemSource { | |
let itemSource = UIImageActivityItemSource() | |
itemSource.image = self | |
itemSource.title = title | |
itemSource.url = url | |
return itemSource | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment