5

This is the workflow of my app: User can select a default printer from app's settings page and will use this default printer to print every time directly without any print preview dialogue.

We can select a printer using UIPrinterPickerController:

let printerPicker = UIPrinterPickerController(initiallySelectedPrinter: nil)
printerPicker.present(from: CGRect(x: 0, y: 0, width: 600, height: 500), in: self, animated: true) { (printerPicker, userDidSelect, error) in
    if userDidSelect {
        //Here get the selected UIPrinter
        let defaultPrinter = printerPicker.selectedPrinter
    }
}

After getting the UIPrinter, we can't directly save the UIPrinter object to UserDefaults, which is not a UserDefault support type.

Is there any other options to save UIPrinter to UserDefaults or any other way to save a default printer.

Arasuvel
  • 2,971
  • 1
  • 25
  • 40
anas.p
  • 2,246
  • 19
  • 26
  • According to https://developer.apple.com/documentation/uikit/uiprinter, you can save a printer's URL, and recreate the printer from that saved URL, but I never tried that myself. – Martin R Jan 25 '18 at 12:36
  • 1
    See also https://stackoverflow.com/a/40610378 – That's Objective-C, but easily translated to Swift. – Martin R Jan 25 '18 at 12:45

1 Answers1

3

You can store custom objects by NSKeyedArchiver. For that it to be encodable they must implement the NSCoding protocol.

But you can't store a UIPrinter instance in NSUserDefaults. After some research I have found this link. Which says:

You can't store a UIPrinter instance in NSUserDefaults. What you can do is save the printer's URL and then when your app starts again and you need the UIPrinter, read the URL from NSUserDefaults and use UIPrinter printerWithURL:.

Arnab
  • 4,216
  • 2
  • 28
  • 50