Airprint iOS Tutorial

With Airprint-enabled printers it is possible to print wireless from an iPhone or an iPad. In this tutorial the text within a Text View will be printed. This tutorial is made with Xcode 10 and built for iOS 12.

Project Setup

Open Xcode and create a new Single View App.

For product name, use IOSAirPrintTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

To test the AirPrint ability we need to install the Printer Simulator. Go to download Additional Tools for the current Xcode Release

Open the Printer Simulator. The Simulator has some virtual printers included which we can use in our application.

Storyboard Setup

Go to the Storyboard and drag a Text View to the main view. Also drag a button to the main view and place it below the Text View. Set the button's title to Print.

Select the Resolve Auto Layout Issues button and select Reset to Suggested Constraints.

The Storyboard should look like this.

Outlet and Action Connections

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Ter Text View to the ViewController class and create the following Outlet

Ctrl and drag from the Button to the ViewController class and create the following Action.

Code Implementation 

Implement the printText method

 @IBAction func printText(_ sender: Any) {
    // 1
    let printController = UIPrintInteractionController.shared
    // 2
    let printInfo = UIPrintInfo(dictionary:nil)
    printInfo.outputType = .general
    printInfo.jobName = "print Job"
    printController.printInfo = printInfo
    // 3
    let formatter = UIMarkupTextPrintFormatter(markupText: textView.text)
    formatter.perPageContentInsets = UIEdgeInsets(top: 72, left: 72, bottom: 72, right: 72)
    printController.printFormatter = formatter
    // 4
   printController.present(animated: true, completionHandler: nil)
  1. The UIPrintInteractionController presents the user interface and manages the printing.

  2. The UIPrintinfo object contains information about the print job, This information is assigned to the printInfo property of the UIPrintInteractionController.

  3. The printing text can be formatted. here we define the insets for the printing page

  4. The user is presented the iPhone printing interface to select a printer and the number of copies

Run Project

Build and Run the project. Select the Print Button and choose a printer.

You can download the source code of the IOSAirPrintTutorial at the ioscreator repository on Github.