Jim Barber
Jim Barber

Reputation: 2139

Printing in iOS from Swift in XCode 6 beta 7

Here is the code I use for Swift airprinting with beta 6 and it worked fine:

@IBAction func button3Tapped() {
    var pic:UIPrintInteractionController = .sharedPrintController()
    var viewpf:UIViewPrintFormatter = myTextView.viewPrintFormatter()
    pic.delegate = self
    pic.showsPageRange = true
    pic.printFormatter = viewpf
    if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
        pic.presentFromRect(self.myButton3.frame, inView:self.view, animated:true, completionHandler: nil)
    } else {
        pic.presentAnimated(true, completionHandler: nil)
    }
}

Of course, beta 7 broke it with a "Value of optional type 'UIPrintInteractionController' not unwrapped; did you mean to use ! or ??" on the first var line. Unfortunately the XCode suggested fix doesn't fix it, and I'm not smart enough to figure it out myself!

Upvotes: 4

Views: 1566

Answers (1)

Tim
Tim

Reputation: 60150

Xcode 6 beta 7 audited much of the Cocoa Touch API for how it exposes optional values – that is, those that could possibly be nil. It looks like the shared print controller is one such value. Opening the Swift version of the header for UIPrintInteractionController, I see:

class func sharedPrintController() -> UIPrintInteractionController?

The type with a trailing question mark – UIPrintInteractionController? – indicates that the return value of sharedPrintController() could be an instance of UIPrintInteractionController or it could be nil.

If you are confident that, in the situation you call that method, it will always return a non-nil value, you can immediately force this optional value to "unwrap" into an instance of UIPrintInteractionController:

var pic = UIPrintInteractionController.sharedPrintController()!
// the rest of your code

On the other hand, if you think you might ever get nil from that method, you can use Swift's optional binding syntax to check that case and continue using pic only if it is non-nil:

if let pic = UIPrintInteractionController.sharedPrintController() {
    // the rest of your code
}

Either way, Xcode is telling you that you now need to deal with the fact that the shared print controller is exposed as an optional value in beta 7.

Upvotes: 3

Related Questions