iosswiftuiwebviewuiactivityviewcontrollerairprint

How to print a UIWebView via UIActivityViewController?


I have a view controller containing a UIWebView and a toolbar with an action/share button. This initializes and presents a UIActivityViewController object. Depending on whether I supply the activityItems parameter with either the web view's URL or the URL's corresponding absoluteString, different actions are offered, but the Print option is never shown (nor offered in the "more" section).

I do know how to print the web view contents explicitly using UIPrintInfo and UIPrintInteractionController, but that would be a separate toolbar button whereas I want to simply include the system's Print option into the activity button row. I assume printing a web view does not need any explicit coding.

What can I do?


Solution

  • You can create Custom Activity For UIActivityCotnroller like this,

     import UIKit
    
    protocol CustomActivityDelegate : NSObjectProtocol
    {
        func performActionCompletion(actvity: CustomActivity)
    }
    
    
    class CustomActivity: UIActivity {
    
        var delegate: CustomActivityDelegate?
    
    
        override class var activityCategory: UIActivityCategory {
            return .action
        }
    
        override var activityType: UIActivityType? {
            guard let bundleId = Bundle.main.bundleIdentifier else {return nil}
            return UIActivityType(rawValue: bundleId + "\(self.classForCoder)")
        }
    
        override var activityTitle: String? {
            return "You title"
        }
    
        override var activityImage: UIImage? {
            return <Your activity image >
        }
    
        override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
            return true
        }
    
        override func prepare(withActivityItems activityItems: [Any]) {
            //
        }
    
        override func perform() {
            self.delegate?.performActionCompletion(actvity: self)
            activityDidFinish(true)
        }
    }
    

    You can initialize this activity some thing like this

    let customActivity = CustomActivity()
    customActivity.delegate = self
    

    And you can add this custom activity while preparing UIActivityController

    let activityViewController : UIActivityViewController = UIActivityViewController(activityItems: [customActivity], applicationActivities: nil)
    

    and you will also need to implement the call back method

    func performActionCompletion(actvity: CustomActivity)
    {
       //Perform you task
    }
    

    Note : This is just pseudo code, might contain error or syntax problems