Kuang Ming, iOS Dev. GitHub: KeithBird Twitter: @KeithBirdkth Blog: Kth App: Syntax tree

Review: Shiye, iOS development. Swift and NodeJS fans

This paper is based on Session 10166 10167 10235 10236

The author compiled this tutorial and some code practices in WWDC into a tutorial by DocC technology and put it in the WWDocC code base

preface

Apple has put a lot of effort into WWDC video, but the official documentation for developers is often so bad that there is even a website that counts No Overview Available. It’s been surveyed that only around 30% of iOS developers learn apis from official documentation, and Paul Hudson also wished to write Reimagining Apple’s Documentation before WWDC 21.

But SwiftUI and Catalyst Tutorials remain two streams, developers’ oases in the documentation desert. Apple obviously didn’t have time to provide such vivid tutorials for every technology, so it made this capability available to developers via the Documentation Compiler (DocC) (in the same way that the iPad doesn’t have a calculator). Of course DocC can also be used to document their open source projects to speed up the promotion and construction of the project.

Compilation of documents

DocC generates the text content of the document by compiling the document comments in the source code and the docC-specific document file. The text content is organized into the final document by the links we will write next, and the interface structure extracted after the source code is compiled.

You can complete the compilation by clicking on Product > Build Documentation from the menu bar. You can also add this step to the Build process by setting Build Documentation during ‘Build’ to Yes in the Documentation Compiler of the Building Settings. To learn how to compile using the command line, see the “Publishing of documents” section.

Compiling document comments

Xcode first compiles the code source files and extracts the public API information (such as profiles, parameter descriptions, return value descriptions, and so on) from the document annotations to generate some document content as part of the production of the DocC Archive. Thus, by default, DocC generates documents organized by interface type and interface structure simply by compiling the source code.

Compiling document files

Consider supplementing document annotations with the Documentation Catalog when you have the following requirements:

  • The framework and main interfaces are introduced on the document front page.
  • You need to customize the structure of organizational documents.
  • Explain open source frameworks in detail through articles.
  • Best practices are guided step-by-step through tutorials.
  • The document contains images and videos.

You can create a new documentation catalog and place it in the same directory as the source code in the Swift package. You can also check Include Documentation when creating a Swift Framework project.

DocC will combine the public API information in the Swift Compiler with the document contents in the Documentation Catalog to produce a richer DocC Archive document file.

Format of comments

Hold down the Command key and click on the interface name and select Add Documentation to automatically generate the template for Documentation annotations. In the template, you can fill in the interface summary, description, parameter description, return value description, throw description, and so on. These contents are written in the format of markup, which will be used many times in the writing of the document and can be learned in Formatting Your Documentation Content.

/// Eat the provided specialty sloth food.
///
/// Sloths love to eat while they move very slowly through their rainforest 
/// habitats. They're especially happy to consume leaves and twigs, which they 
/// digest over long periods of time, mostly while they sleep.
///
/// When they eat food, a sloth's `energyLevel` increases by the food's `energy`.
///
/// - Parameters:
/// - food: The food for the sloth to eat.
/// - quantity: The quantity of the food for the sloth to eat.
///
/// - Returns: The sloth's energy level after eating.
///
/// - Throws: `SlothError.tooMuchFood` if the quantity is more than 100.
mutating public func eat(_ food: Food.quantity: Int) throws -> Int {.}
Copy the code

By writing the above documentation comments and compiling, you can see the following information in the corresponding interface documentation:

It can also be viewed via Quick Help (optiong + click on the interface name to pop up) :

Documentation

The documents in DocC are divided into three categories: Reference documents, which are widely used in official documents and are used to specifically introduce interfaces. The format is more flexible and used for Articles that describe the constructs behind the framework, such as the connections between different components. Tutorials help users complete best practices with interactive step-by-step guidance.

We’ll start with the home page in the reference document:

Write the content

By default, DocC forms a home page that acts as an entry point for documents by listing public interfaces and grouping them by type.

But we can also customize it by following these steps. First, all DocC files must be valid in the documentation Catalog with the same name as the project. We can create a new Empty file in the documentation as the first page:

Rename the.md file with the same project name, and the content in the title ““ should also be the project name so that Xcode can associate them at compile time. Below the title is a summary, and then you can use markup syntax to add text, code, images, video, and more to the document’s home page.

# ``SlothCreator``

Catalog sloths you find in nature and create new adorable virtual sloths.
Copy the code

Rewrite the structure

After the content of the document we have just written, you will notice that the common interfaces are listed by type by default in the Topic Topic. If you want to reorganize them as you like, you can append the Topic section to the home page file:

Where ### is used to name each group. – < doc: / tutorials/SlothCreator > used to link the tutorials called SlothCreator file directory. ““ is used to link to the corresponding interface document, whose content must be the full path of the interface, such as’ ‘SlothCreator/Sloth/eat(_:quantity:)’ ‘.

After Topics are refactored, you can see that the structure of the left navigation bar changes as well:

If self-written Topics leave out some public interfaces or DocC article and tutorial directories, they will still be appended to the custom structure by default (grouped by type) to ensure the integrity of the document.

In addition to the home page, the reference documents for each interface can also be customized. Simply create a new Extension File in Documentation, change the File name to the interface name, and fill in the full path to the interface in the first line ““. The document content and Topics are written in the same way as the home page and are added to the document content generated by the document comments.

# ``SlothCreator/Sloth``

## Topics

### Creating a Sloth

- ``init(name:color:power:)``
- ``SlothGenerator``...Copy the code

Note that ““ after the title # is used to give Xcode a hint that the corresponding interface name needs to be linked to this document. The following ““ in the body is used to generate a link to jump to the corresponding interface document. Members inside the interface that are not fully listed are appended to the end by default, just like the home page.

Override annotations

The content in the Extension File is appended by default to the content generated by compiling the document’s comments, but at some point we want to rewrite the reference document completely. In this case, we need to indicate overwriting under the title:

# ``SlothCreator/Sloth``

@Metadata {
    @DocumentationExtension(mergeBehavior: override)
}
This content overrides the profile generated by the source code.## OverviewThis content overrides the source code generation overview. .Copy the code

Note that this parameter change does not affect the content in Topics.

Supplementary article

The document is written under the title of interface and has a relatively rigid structure. Articles are a more flexible way to complement other aspects of the framework. You can create the Article by creating a new Article File in Documentation.

By default, articles appear in the home page and navigation bar as the topmost level in the structure. Therefore, unlike anything we’ve written before, the title of the article is general content rather than a quote. There is no special requirement for the file name, which is used only when the article is referenced. The body of the article is also written with markup, and Topics can be added at the end to organize the document structure.

# Getting Started with Sloths

Create a sloth and assign personality traits and abilities.

## Overview

Sloths are complex creatures that require careful creation and a suitable
habitat.

...

## Topics

### Essentials

- <doc:/tutorials/SlothCreator>
- ``Sloth``
Copy the code

Interactive tutorial

Interactive Tutorials are hard to describe, and readers who have never done them can refer to SwiftUI Tutorials and Catalyst Tutorials. Tutorials are also one of the highlights of DocC, which consists of a tutorial directory and a tutorial page:

The file format

Tutorials need to be built into the Documentation catalog. You can create Tutorial directories and Tutorial pages by creating a Tutorial Table of Contents and Tutorial File in Documentation, both of which are.tutorial files. Only the tutorial directory can jump to the tutorial page, so you must write the tutorial directory even if there is only one tutorial. By default, the Documentation Catalog contains a Resources folder for storing DocC documents, articles, images, videos, code, and other Resources used in tutorials.

As shown, the images used in the Markup file have official naming suggestions:

Only the image name and extension name are required. ~dark indicates that the image will be used in Dark mode, and the content followed by @ indicates the image used by devices with different display scales. With the naming method described above, just fill in the name of the image in the markup file, and the DocC will automatically dynamically adopt the best version of the image in the document. [] is the description of the picture content, which is used to provide voice prompts for the visually impaired.

! [A sloth hanging off a tree.] (sloth)
Copy the code

There is no official naming convention for code resources, and since they are mainly used in step-by-step tutorials, it is recommended to name them tutorial name-chapter Name-number of steps. Swift.

The directory to write

Xcode fills in the template automatically after creating a tutorial directory to help developers get started. The contents of directory filenames and @tutorials (name:) are generally project names.

The @intro directive is followed by the title of the catalog, an overview of the tutorial, and a cover image. The estimated time and Get Started buttons are automatically generated based on the tutorial page information provided later.

The @chapter directive is used to categorize and organize tutorials, including title, image, and tutorial references. Where @tutorialReference can be linked to the corresponding tutorial page using the file name.

A tutorial directory (@tutorials) contains an introduction (@intro) and chapters (@chapters), and a tutorial can have multiple references to tutorial pages (@tutorialReferences).

tutorial

A Tutorial page (@tutorial) contains an introduction (@intro) and sections (@sections). A chapter can contain only one set of Steps (@steps). The Steps below the set of Steps (@step) are the minimum structure.

There is no special requirement for the file name of the tutorial page and it is only used for links. Enter the estimated time for viewing the Tutorial page in @tutorial (time:). The name of the article in which the tutorial is located (SlothCreator Essentials) is automatically displayed. The format of the tutorial page @intro is the same as that of the directory.

The structure under the tutorial page is chapter (@section). The chapter uses @contenandMedia to display the introduction, and you can adjust the layout of media and text, such as pictures, by filling in the parameters in (Layout:).

@step contains a step-by-step description on the left, the file name the developer wants to see in the document, the actual file name of the code snippet, and a preview:

It can be seen that the preview image is not generated by code compilation, so the developer needs to save screenshots in advance. It is recommended to name the source files and preview images properly and group them in the previously mentioned Resource folder to avoid confusion.

@Code is not required, @Step could be written like this:

@Step {
    Create a new project using the iOS App template.

    @Image(source: image-Tutorial1-Section1-Step1.png, alt: "")
}
Copy the code

The effect is as follows:

Note that the Alt parameter in @image (source: image.png, Alt: “”) cannot be omitted. The example code in the Image above will get an error due to its absence. Alt stands for Alternative Text, which will be read by VoiceOver, a screen reader, to help the visually impaired.

Document publishing

After compiling the document, Xcode generates a Documentation Archive file, which you can export directly from the document:

You can also use the command line tool to compile to the specified address:

xcodebuild docbuild
    -scheme SlothCreator
    -derivedDataPath ~/Desktop/SlothCreatorBuild
Copy the code

During compilation, Xcode generates a large number of files at the target address, which can be located using the following instructions:

find ~/Desktop/SlothCreatorBuild
    -type d -name '*.doccarchive'
Copy the code

Simply send the.doccarchive package to another developer, who can open it with Xcode to view the document. The file package contains CSS, HTML, JS, documents, images, and videos.

Because the file contains HTML to render the document’s content, developers can even host the document on a web site. Using Apache as an example, here are the steps required to host documents on a web site:

  1. Copy the.doccarchive file to the directory the server uses to serve the file.
  2. Adding a rule to the server will result in/documentation/tutorialsAt the beginning of the URLroutingTo the index. The HTML.
  3. Add another rule to support access to resources such as CSS and images in a file.

To locate documents, reference documents and article urls need to start with /documentation, and tutorial urls need to start with /tutorials. For example, if you need to locate a protocol named SlothGenerator in the SlothCreator document, the URL is as follows:

https://www.example.com/documentation/SlothCreator/SlothGenerator
Copy the code

Here is what is configured in the.htaccess file:

# Enable custom routing.
RewriteEngine On

# Route documentation and tutorial pages.
RewriteRule ^(documentation|tutorials)\/.*$ SlothCreator.doccarchive/index.html [L]

# Route files within the documentation archive.
RewriteRule ^(css|js|data|images|downloads|favicon\.ico|favicon\.svg|img|theme-settings\.json|videos)\/.*$ SlothCreator.doccarchive/$0 [L]
Copy the code

Apple’s promise to open source DocC this year, along with an app that can host unofficial documents, will simplify the configuration process by making DocC’s document workflow accessible without Xcode.

Afterword.

Gone are the days of “Talk is cheap, show me the code”. A lively document is not only a great addition to open source frameworks, it is also a great tool for reducing communication costs and popularizing new technologies. As Internet companies get bigger and bigger, technical documentation becomes a huge barrier to teamwork, which can be managed like a needle in a haystack. DocC is a new solution provided by Apple. In the foreseeable future, technology companies, open source communities and IT educational institutions will use this technology to optimize their document management methods and build a more efficient infrastructure for technical communication between programmers.

Pay attention to our

We are the Veteran Driver Tech Weekly, a tech newsletter that continues to pursue premium iOS content. Welcome to follow.

Focus on politeness, focus on[Old Driver Technology Weekly], reply “2021” and get the internal reference of 2017/2018/2019/2020

Support the author

I recommend the WWDC21 Insider column, which contains 102 articles about WWDC21 and is the source of this article. If you are interested in the rest of the content, please click the link to read more

WWDC internal reference series is led by the old driver organization of high-quality original content series. We’ve been doing it for a couple of years, and it’s been good. It is mainly for the annual WWDC content, do a selection, and call on a group of front-line Internet iOS developers, combined with their actual development experience, Apple documents and video content to do a second creation.