I want to add a share button to my app. Can I share a complete view controller so that when a user clicks on the shared link it comes to the view controller that was shared?
So far I have only found things like how to share images and text.
This is my code:
#IBAction func shareButtonTapped(_ sender: UIBarButtonItem) {
let items = [self]
let ac = UIActivityViewController(activityItems: items, applicationActivities: nil)
present(ac, animated: true)
}
At the moment I can only share a string.
extension DetailViewController: UIActivityItemSource {
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return "Test"
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
return "Test"
}
}
Related
I'm sharing a URL via UIActivityViewController. I'd like to see "Open in Safari" or "Open in browser" appear on the share sheet, but it doesn't. Is there a way to make this happen?
Note: I am not interested in solutions that involve adding somebody else's library to my app. I want to understand how to do this, not just get it to happen. Thanks.
Frank
Yes, you could add your custom action to Share sheet in iOS
You would have to copy this class.
class MyActivity: UIActivity {
var _activityTitle: String
var _activityImage: UIImage?
var activityItems = [Any]()
var action: ([Any]) -> Void
init(title: String, image: UIImage?, performAction: #escaping ([Any]) -> Void) {
_activityTitle = title
_activityImage = image
action = performAction
super.init()
}
override var activityTitle: String? {
return _activityTitle
}
override var activityImage: UIImage? {
return _activityImage
}
override var activityType: UIActivity.ActivityType {
return UIActivity.ActivityType(rawValue: "com.someUnique.identifier")
}
override class var activityCategory: UIActivity.Category {
return .action
}
override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
return true
}
override func prepare(withActivityItems activityItems: [Any]) {
self.activityItems = activityItems
}
override func perform() {
action(activityItems)
activityDidFinish(true)
}
}
Please go through the class you might need to change a few things.
This is how you use it.
let customItem = MyActivity(title: "Open in Safari", image: UIImage(systemName: "safari") ) { sharedItems in
guard let url = sharedItems[0] as? URL else { return }
UIApplication.shared.open(url)
}
let items = [URL(string: "https://www.apple.com")!]
let ac = UIActivityViewController(activityItems: items, applicationActivities: [customItem])
ac.excludedActivityTypes = [.postToFacebook]
present(ac, animated: true)
I have done this for one action, and tested it, it works.
Similarly you could do it for other custom actions.
For more on it refer this link.
Link To Detailed Post
I wanted to further customize how content is shared from my app and instead of providing UIActivityViewController with image and title use the UIActivityItemSource protocol to implement methods that provide this content.
So I created extension for my model Scan like this:
extension Scan: UIActivityItemSource {
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return self.title as Any
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
return self.orderedDocuments.map({ $0.image }) as Any
}
func activityViewController(_ activityViewController: UIActivityViewController, thumbnailImageForActivityType activityType: UIActivity.ActivityType?, suggestedSize size: CGSize) -> UIImage? {
return self.thumbnailImage
}
func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String {
return "Scan from: \(String(describing: self.created))"
}
}
But when I pass instance of Scan to the UIActivityViewController it opens but it is empty. I cannot see the title, preview or the actual images.. These methods are getting called.
I am presenting the UIActivityViewController like this as there is not much to customize:
func share(_ scan: Scan) {
let shareController = UIActivityViewController(activityItems: [scan], applicationActivities: nil)
present(shareController, animated: true)
}
The Scan is Core Data entity but I tried creating separate class just for sharing and that did not work either.
EDIT: So I got some progress with metadata like this:
func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
guard let image = self.orderedDocuments.first?.image else { return nil }
let imageProvider = NSItemProvider(object: image)
let metadata = LPLinkMetadata()
metadata.imageProvider = imageProvider
metadata.title = title
return metadata
}
It at least shows proper title and thumbnail. I have seen some apps even displaying subtitle and file size which I guess is not possible for in-memory images?
I still have issues with sharing more than one image.
My updated activity controller methods:
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
return self.orderedDocuments.first?.image
}
func activityViewController(_ activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: UIActivity.ActivityType?) -> String {
return kUTTypePNG as String
}
Regarding:
I have seen some apps even displaying subtitle and file size which I
guess is not possible for in-memory images?
It's silly, but can be done with:
linkMetaData.originalURL = URL(fileURLWithPath: "Insert whatever info here")
For example, for a result like this (custom thumbnail, custom title and subtitle with file size):
... the code is:
func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
let linkMetaData = LPLinkMetadata()
// Thumbnail
linkMetaData.iconProvider = NSItemProvider(object: someValidUIImage)
// Title
linkMetaData.title = "Ohay title!"
// Subtitle with file size
let prefix = "PNG Image"
let fileSizeResourceValue = try! someValidURL.resourceValues(forKeys: [.fileSizeKey])
let fileSizeInt = fileSizeResourceValue.fileSize
let byteCountFormatter = ByteCountFormatter()
byteCountFormatter.countStyle = .file
let fileSizeString = byteCountFormatter.string(fromByteCount: Int64(fileSizeInt))
let suffix = "・\(fileSizeString)"
//👇
linkMetaData.originalURL = URL(fileURLWithPath: "\(prefix)\(suffix)")
return linkMetaData
}
In my application, I'm using the QuickLook framework to view the document files such as pdf, ppt, doc, etc. etc. But due to privacy concerns, I don't want that the user can share this document with others so please let me know how to disable/hide the share button and also the copy-paste option.
I know this question can be asked by a number of times and tried many solutions but nothing works for me
hide share button from QLPreviewController
UIDocumentInteractionController remove Actions Menu
How to hide share button in QLPreviewController using swift?
Hide right button n QLPreviewController?
Please suggest to me to achieve this.
Here is my demo code:
import UIKit
import QuickLook
class ViewController: UIViewController {
lazy var previewItem = NSURL()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func displayLocalFile(_ sender: UIButton){
let previewController = QLPreviewController()
// Set the preview item to display
self.previewItem = self.getPreviewItem(withName: "samplePDf.pdf")
previewController.dataSource = self
self.present(previewController, animated: true, completion: nil)
}
#IBAction func displayFileFromUrl(_ sender: UIButton){
// Download file
self.downloadfile(completion: {(success, fileLocationURL) in
if success {
// Set the preview item to display======
self.previewItem = fileLocationURL! as NSURL
// Display file
let previewController = QLPreviewController()
previewController.dataSource = self
self.present(previewController, animated: true, completion: nil)
}else{
debugPrint("File can't be downloaded")
}
})
}
func getPreviewItem(withName name: String) -> NSURL{
// Code to diplay file from the app bundle
let file = name.components(separatedBy: ".")
let path = Bundle.main.path(forResource: file.first!, ofType: file.last!)
let url = NSURL(fileURLWithPath: path!)
return url
}
func downloadfile(completion: #escaping (_ success: Bool,_ fileLocation: URL?) -> Void){
let itemUrl = URL(string: "https://images.apple.com/environment/pdf/Apple_Environmental_Responsibility_Report_2017.pdf")
// then lets create your document folder url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent("filename.pdf")
// to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path) {
debugPrint("The file already exists at path")
completion(true, destinationUrl)
// if the file doesn't exist
} else {
// you can use NSURLSession.sharedSession to download the data asynchronously
URLSession.shared.downloadTask(with: itemUrl!, completionHandler: { (location, response, error) -> Void in
guard let tempLocation = location, error == nil else { return }
do {
// after downloading your file you need to move it to your destination url
try FileManager.default.moveItem(at: tempLocation, to: destinationUrl)
print("File moved to documents folder")
completion(true, destinationUrl)
} catch let error as NSError {
print(error.localizedDescription)
completion(false, nil)
}
}).resume()
}
}
}
//MARK:- QLPreviewController Datasource
extension ViewController: QLPreviewControllerDataSource {
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
controller.navigationItem.rightBarButtonItem = nil
return self.previewItem as QLPreviewItem
}
}
Please provide your suggestion to do so or any other framework to view different file formats.
Here is the image
Find below adopted my approach to your code (with modifications to test locally, but the code should be clear). The idea is
a) to override, which is completely allowed by API, needed classes to intercept modification
b) to use intentionally own UINavigationController, as only one navigation controller can be in stack
So here is code:
// Custom navigation item that just blocks adding right items
class MyUINavigationItem: UINavigationItem {
override func setRightBarButtonItems(_ items: [UIBarButtonItem]?, animated: Bool) {
// forbidden to add anything to right
}
}
// custom preview controller that provides own navigation item
class MyQLPreviewController: QLPreviewController {
private let item = MyUINavigationItem(title: "")
override var navigationItem: UINavigationItem {
get { return item }
}
}
class MyViewController : UIViewController, QLPreviewControllerDataSource {
lazy var previewItem = NSURL()
override func loadView() {
let view = UIView()
view.backgroundColor = .white
// just stub testing code
let button = UIButton(type: .roundedRect)
button.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
button.setTitle("Show", for: .normal)
button.addTarget(self, action:
#selector(displayLocalFile(_:)), for: .touchDown)
view.addSubview(button)
self.view = view
}
#objc func displayLocalFile(_ sender: UIButton){
let previewController = MyQLPreviewController() // << custom preview
// now navigation item is fully customizable
previewController.navigationItem.title = "samplePDF.pdf"
previewController.navigationItem.leftBarButtonItem =
UIBarButtonItem(barButtonSystemItem: .done, target: self,
action: #selector(closePreview(_:)))
// wrap it into navigation controller
let navigationController = UINavigationController(rootViewController: previewController)
// Set the preview item to display
self.previewItem = self.getPreviewItem(withName: "samplePDF.pdf")
previewController.dataSource = self
// present navigation controller with preview
self.present(navigationController, animated: true, completion: nil)
}
#objc func closePreview(_ sender: Any?) {
self.dismiss(animated: true) // << dismiss preview
}
func getPreviewItem(withName name: String) -> NSURL{
// Code to diplay file from the app bundle
let file = name.components(separatedBy: ".")
let path = Bundle(for: type(of: self)).path(forResource: file.first!, ofType: file.last!)
let url = NSURL(fileURLWithPath: path!)
return url
}
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return self.previewItem as QLPreviewItem
}
}
In my application, I have added my share extension it's working fine, But I face One problem When I invite app through UIActivityViewController I show my application Extension. How can I hide my application Extension of my own application?
You can do it by adding your Extension activity type in the list of excluded activity types:
let activityViewController = UIActivityViewController(activityItems: <your items>, applicationActivities: <your supported application activities>)
let extensionActivityType = UIActivityType(<your extension activity type id>)
activityViewController.excludedActivityTypes = [extensionActivityType]
Sorry for late but hope this ans will surly help you out.
First of all define below lines in your code
class ActionExtensionBlockerItem: NSObject, UIActivityItemSource {
func activityViewController(_ activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: UIActivityType?) -> String {
return "com.your.unique.uti";
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType) -> Any? {
// Returning an NSObject here is safest, because otherwise it is possible for the activity item to actually be shared!
return NSObject()
}
func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivityType?) -> String {
return ""
}
func activityViewController(_ activityViewController: UIActivityViewController, thumbnailImageForActivityType activityType: UIActivityType?, suggestedSize size: CGSize) -> UIImage? {
return nil
}
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return ""
}
}
Here com.your.unique.uti is your Application group identifier
and then while presenting activityViewController use code below
let activityViewController = UIActivityViewController(activityItems: [/* Other Items To Share, */ ActionExtensionBlockerItem()], applicationActivities: nil)
I'm trying to share an image with text through UIActivityViewController. If I do this:
let activityVC = UIActivityViewController(activityItems: [text, image], applicationActivities: nil)
self.presentViewController(activityVC, animated: true, completion: nil)
Everything works fine. The problem is that I only want to share the image with certain activity types. i.e. when a user shares to Facebook I don't want to have an image, for everything else I do though. My problem is this stupid method is never called:
optional func activityViewController(_ activityViewController: UIActivityViewController,
thumbnailImageForActivityType activityType: String?,
suggestedSize size: CGSize) -> UIImage?
Which should be becuase it's defined in UIActivityItemSource protocol. Is there any work around to this?
So I believe to have made some headway here. Turns our if you pass multiple values of self when instantiating UIActivityViewController you can return multiple values in the itemForActivityType delegate method. So if I do this:
let activityVC = UIActivityViewController(activityItems: [self, self], applicationActivities: nil)
I can return different values like this:
func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {
if activityType == UIActivityTypePostToFacebook {
return ["hello", "world"]
}
else {
return ["goodnight", "moon"]
}
}
However, it seems that you can only return two values of the same type.
My new question is now, how would I return both an image and text?? The hunt continues...
In order to share two different set of content you have to create two different itemsource
we can set different text content for different activity type.Add the MyStringItemSource class to your viewcontroller
SourceOne:
class MyStringItemSource: NSObject, UIActivityItemSource {
#objc func activityViewControllerPlaceholderItem(activityViewController: UIActivityViewController) -> AnyObject {
return ""
}
#objc func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {
//You can pass different text for for diffrent activity type
if activityType == UIActivityTypePostToFacebook {
return "String for facebook"
}else{
return "String for Other"
}
}
}
Our requirement is to add image to all activity type except FB,to do that add the MyImageItemSource class in your VC.
SourceTwo:
class MyImageItemSource: NSObject, UIActivityItemSource {
#objc func activityViewControllerPlaceholderItem(activityViewController: UIActivityViewController) -> AnyObject {
return ""
}
#objc func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {
//This one allows us to share image ecxept UIActivityTypePostToFacebook
if activityType == UIActivityTypePostToFacebook {
return nil
}
let Image: UIImage = UIImage(data: NSData(contentsOfURL: NSURL(string: "https://pbs.twimg.com/profile_images/604644048/sign051.gif")!)!)!
return Image
}
}
Now we are ready to set UIActivityViewController,here we go
#IBAction func Test(sender: AnyObject) {
let activityVC = UIActivityViewController(activityItems: [MyStringItemSource(),MyImageItemSource()] as [AnyObject], applicationActivities: nil)
//Instead of using rootviewcontroller go with your own way.
if let window = (UIApplication.sharedApplication().delegate as? AppDelegate)?.window
{
window.rootViewController?.presentViewController(activityVC, animated: true, completion: nil)
}
}
TWITTER Shared Dialogue:
Contains image and given text
FB Share Dialogue:
Contains only the given text