Swift Playgrounds book開發流程簡介

Swift Playgrounds book開發流程簡介

  • Swift Playgrounds 是一款革命性的 iPad 應用,可以用強大的 Swift 語言進行教學。蘋果推崇在 Swift Playgrounds 上人人都能使用 Swift 編程的原則,讓所有人都能學習、編碼以及教授代碼課程。

  • 蘋果在 Swift Playgrounds 應用上提供了很多學習編程相關的 Playground Book,本文就通俗的稱之為電子書。

  • Playground 電子書(.playgroundbook),它能夠幫助你管理內容,生成瀏覽目錄,使你更容易找到自己想要學習的章節及頁面,下面是 Playground 電子書頁面的一張截圖,感受一下:


    圖2:Playground book運行效果

    圖的左邊是源代碼編輯器,右邊是“所見即所得”的實時視圖.

1. Swift Playgrounds app 項目結構

1.1 Playground book總的結構

一個Playground book有三大部分構成:

  • PlaygroundBook : 左側展示書籍的章節描述信息
  • Book_Sources : 資源包
  • LiveViewApp : 右側展示的LiveView場景內容


    圖1:Playground book結構

最終顯示結果如下:

圖2:Playground book運行效果
  • 如上圖,你在左側可以編寫相關swift代碼,點擊運行Run My Code 便可以在右側場景看到代碼執行的效果。
  • 左側的章節對應的右PlaygroundBook工程開發,不能實時聯機調式
  • 右側的實時場景是由LiveViewTestApp工程開發,可以連接調試。

1.2 Playground 電子書的目錄格式

  • Playground 電子書,是一個帶有 .playgroundbook 后綴名的文件,可以理解為一個文件夾資源包,它是一個嵌套的文件夾結構格式,其中包括所有資源文件。
Playground 電子書的目錄格式

我們根據目錄結構主要把它區分三個層次:

  • Contents :Playground 電子書根目錄,包含所有資源文件,屬于最高層級,其中包含 Chapters 文件夾以及一個配置文件 Manifest.plist。

  • Chapters :總章節文件夾,包含所有章節文件夾。每個章節文件夾都帶有 .playgroundchapter 后綴,并且其目錄下都包含 Pages 文件夾以及一個配置文件 Manifest.plist。

  • Pages : 總頁面文件夾,包含所有頁面文件夾,每個頁面文件夾都帶有 .playgroundpage 后綴,其目錄下都包含著自己運行所需要的所有資源以及一個配置文件 Manifest.plist。

目錄結構

上述的三個目錄下都有屬于自己 Manifest 配置文件,有什么作用呢?

  1. Contents 下的Manifest.plist 用于描述電子書的信息
  2. Chapters下面的Manifest.plist用于描述章節及目錄信息
  3. Pages下面的Manifest.plist用于描述頁面信息以及其行為

此外還有兩種文件夾,一般放置與 Contents 目錄下:

  1. Sources:輔助的 Swift 源文件,如果放置在 Contens 目錄下,意味著所有 Page 都能訪問,屬于全局范疇。
  2. Resources:電子書的資源文件,一般放置一些圖片、音頻文件等等,其他類似于 Sources 文件夾。

1.3 PlaygroundBook模板工程目錄結構

圖3:Playground工程目錄結構1
  • 如上圖所示, 最終生成的kylPlaygroundBook.playgroundbook 是可以發布的產品,可以通過airdrop 發送到ipad上面的playground運行。
  • 工程主要有兩部分組成PlaygroundBook和LiveViewTestApp. 以前meebot1.0 是分別新建的兩個項目,最后合成在一起。
  • PlaygroundBook是左側用于顯示的章節內容信息。
  • LiveViewTestApp 是用于右側實時展示的場景。

1.3.1 PlaygroundBook工程結構

1.3.1.1 Manifest.plist配置文件

Manifest配置文件
  • Manifest.plist是Playground Book 的配置信息文件,可以在這個配置文件中加入 書名、封面圖片、版本等信息。

對應必選的字段如下

  • Name: Playground Book 的名字,會在 Swift Playgrounds 被學習者看到。
  • Version:Playground Book 所用的格式版本號,使用固定字符串:6.0
  • ContentVersion: Playground Book 的版本號,如 1.0.2, 用于 Book 更新。
  • ContentIdentifier: Playground Book 的唯一標識符,用于區別不同的 Playground Book,采用 reverse-DNS 命名規則,如:com.ubtech.playgroundbook.
  • DeploymentTarget: 對 iOS 設備的系統版本最低要求,如設置為: ios11.3, 則說明只有 iOS11.3以上的設備才能運行你的 Playground Book。
  • DevelopmentRegion: 默認語言和區域。
  • UserModuleMode: 用于確定學習者對書中用戶可編輯模塊的控制程度的字符串,必須為以下字符串中的某一個:(Full ,Limited ,Disabled)
  • Chapters: Playground Book 所包含的章節信息。Chapters 的內容為包含章節名字的有序數組。如:
<array> <string>Chapter1.playgroundchapter</string> 
<string>Chapter2.playgroundchapter</string>
</array>

對應可選的字段如下

  • ImageReference: Playground Book 封面圖片,寬高比必須為4:3,格式為 .png, 建議大小為 400 x300
  • SwiftVersion: Playground Book 使用的 Swift 版本號,默認為: 5.0
  • MinimumSwiftPlaygroundsVersion: Playground Book 對 Swift Playgrounds app的最低版本號要求。默認為 1.2

2. Swift Playgrounds book 開發

  • 從 WWDC 2016 Swift Playground Books 誕生開始,制作 Playground 電子書是比較麻煩的。
  1. 你要嚴格按照上述所說的文件目錄結構的格式來整理你的文件,如果萬一中間某個處弄錯了,那么在 iPad 上就無法正常運行。像這種操作應該實現自動化生成文件目錄結構,讓開發者更加關注其實現。
  2. 從上面這一條可以看出,調試起來是個坑,很難定位的自己是哪出錯了。在程序上,調試只能以打印 Log 的方式進行,無法進行斷點調試也是個痛點。
  • 為了方便開發,蘋果提供了模板,蘋果推薦按照其模板去開發,不要修改模板工程結構。

2.1 Swift Playgrounds 模板

  • 先下載模板代碼 蘋果官方模板下載

  • Swift Playgrounds 模板是一個幫助制作者調試、快速創建的一個 Xcode 工程,讓制作者更加關注于內容的創建。

  • 這個 Xcode 工程有三個不同的 Target 來幫助你創作屬于你的 Playground 電子書:


    模板1

2.1.1 PlaygroundBook Target

  • 這個 Target 主要用于自動生成 Playground 電子書.


    PlaygroundBook Target
  • 通過 Xcode 目錄可知,這個 Target 所有文件都在 PlaygroundBook 文件夾下,其中包含文章前所說的 Sources 和 PrivateResources(Resources) 文件夾,還有默認包含一個章節以及一個頁面。

2.1.2 Book_Sources Target

  • 這個 Target 我們可以簡單理解為把 Sources 源文件編譯成一個靜態庫,供 LiveViewTestApp Target 使用,這里有個點需要注意,如果你創建了多個 Page,并且需要進行調試的時候要明確你要調試那個 LiveView,從而并進行 Debug 視圖切換。


    Book_Sources Target

2.1.3 LiveViewTestApp Target

  • 這個 Target 目的已經很明確了,就是針對 LiveView 進行調試的, 可以直接連接ipad進行調式。


    LiveViewTestApp Target

2.1.4 模板 三個Target交互

  • 在 Sources 文件夾中有兩個源文件:
  1. LiveViewController.swift
//
//  See LICENSE folder for this template’s licensing information.
//
//  Abstract:
//  An auxiliary source file which is part of the book-level auxiliary sources.
//  Provides the implementation of the "always-on" live view.
//

import UIKit
import PlaygroundSupport

@objc(Book_Sources_LiveViewController)
public class LiveViewController: UIViewController, PlaygroundLiveViewMessageHandler, PlaygroundLiveViewSafeAreaContainer {
    /*
    public func liveViewMessageConnectionOpened() {
        // Implement this method to be notified when the live view message connection is opened.
        // The connection will be opened when the process running Contents.swift starts running and listening for messages.
    }
    */

    /*
    public func liveViewMessageConnectionClosed() {
        // Implement this method to be notified when the live view message connection is closed.
        // The connection will be closed when the process running Contents.swift exits and is no longer listening for messages.
        // This happens when the user's code naturally finishes running, if the user presses Stop, or if there is a crash.
    }
    */

    public func receive(_ message: PlaygroundValue) {
        // Implement this method to receive messages sent from the process running Contents.swift.
        // This method is *required* by the PlaygroundLiveViewMessageHandler protocol.
        // Use this method to decode any messages sent as PlaygroundValue values and respond accordingly.
    }
}
  • 這里需要注意的是 Swift 類被起了個別名
    @objc(Book_Sources_LiveViewController) 暴露給 Objective-C。
  1. LiveViewSupport.swift
//
//  See LICENSE folder for this template’s licensing information.
//
//  Abstract:
//  Provides supporting functions for setting up a live view.
//

import UIKit
import PlaygroundSupport

/// Instantiates a new instance of a live view.
///
/// By default, this loads an instance of `LiveViewController` from `LiveView.storyboard`.
public func instantiateLiveView() -> PlaygroundLiveViewable {
    let storyboard = UIStoryboard(name: "LiveView", bundle: nil)

    guard let viewController = storyboard.instantiateInitialViewController() else {
        fatalError("LiveView.storyboard does not have an initial scene; please set one or update this function")
    }

    guard let liveViewController = viewController as? LiveViewController else {
        fatalError("LiveView.storyboard's initial scene is not a LiveViewController; please either update the storyboard or this function")
    }

    return liveViewController
}


  • 這個源文件僅僅聲明了一個 public 方法,并返回 Storyboard 中的一個控制器實例。
  • 這里可能有個疑惑:LiveViewController 貌似沒有遵循 PlaygroundLiveViewable 協議,怎么沒有報編譯錯誤?原因是在 PlaygroundSupport 組件中就給 UIViewController 加了個擴展,并遵循其協議。
  • 下面我們來看看是如何在 Pages 中的 LiveView 引用的:
//  Abstract:
//  Instantiates a live view and passes it to the PlaygroundSupport framework.
//

import UIKit
import PlaygroundSupport

// Instantiate a new instance of the live view from the book's auxiliary sources and pass it to PlaygroundSupport.
PlaygroundPage.current.liveView = instantiateLiveView()
Pages 中的 LiveView 引用
  • 這里可能有個疑惑:instantiateLiveView 在 Pages 是怎么識別的?

原因是:Sources 文件夾中的源文件屬于 Global files,并且該方法還是 public

  • 我們再來看看 LiveViewTestApp Target 中的 AppDelegate.swift:

import UIKit
import PlaygroundSupport
import LiveViewHost
import Book_Sources

@UIApplicationMain
class AppDelegate: LiveViewHost.AppDelegate {
    override func setUpLiveView() -> PlaygroundLiveViewable {
        // This method should return a fully-configured live view. This method must be implemented.
        //
        // The view or view controller returned from this method will be automatically be shown on screen,
        // as if it were a live view in Swift Playgrounds. You can control how the live view is shown by
        // changing the implementation of the `liveViewConfiguration` property below.
        return Book_Sources.instantiateLiveView()
    }

    override var liveViewConfiguration: LiveViewConfiguration {
        // Make this property return the configuration of the live view which you desire to test.
        //
        // Valid values are `.fullScreen`, which simulates when the user has expanded the live
        // view to fill the full screen in Swift Playgrounds, and `.sideBySide`, which simulates when
        // the live view is shown next to or above the source code editor in Swift Playgrounds.
        return .fullScreen
    }
}

  • setUpLiveView 方法是直接調用 Book_Sources Target 生成的靜態庫調用其方法實現的,當有多個不同的 LiveView 進行調試時,此處要記得更改。

  • 運行LiveView默認是.fullScreen 全屏模式,可以自己修改為.sideBySide半屏模式。

  • 總結一下,交互流程就是:Book里面章節里面的相關代碼最終都會打包成一個Book_Sources Target 生成的靜態庫. 開發是是通過直接調試LiveView target 里面編寫相關代碼,去調用靜態庫里面提供的方法。

3. Swift Playgrounds book 打包發布

3.1 安裝電子書到ipad

如何把制作好的 Playground 電子書安裝到 iPad?

這里有兩種較為常用的方法:

  • AirDrop : 直接把 xx.playgroundbook 文件通過 AirDrop 丟給 iPad。必須現在ipad安裝蘋果的playground app,如果安裝了playground app ,當你在電腦上通過AirDrop共享xx.playgroundbook電子書發送給ipad ,iPad會自動將它安裝到playground里面。

  • iCloud Drive(iCloud 云盤)

3.2 Swift Playgrounds 訂閱 Feeds 格式

  • 我們如何把制作的電子書分享給他人學習呢?
  • 我們一般把一系列的 Playground 電子書相關資源托管至遠端,并把其描述成一個 Feeds JSON 文件,然后 Swift Playgrounds 再通過解析其內容來達到訂閱的目的。下面我們來了解一下該 JSON 的數據格式及結構。
{
    "title": "WWDC Photo Filters",
    "subtitle": "A Collection of Swift Lessons",
    "publisherName": "Holly and Grace",
    "feedIdentifier": "io.github.WWDCPhotoFilters",
    "contactURL": "mailto:example@apple.com", // 訂閱發布者的聯系方式
    "formatVersion": "1.0", //訂閱 Feed 發布版本號
    "documents": [
        {
            "title": "Image Transitions",
            "overviewSubtitle": "CIFilters in the Transition Category.",
            "detailSubtitle": "Filters in CICategoryTransition.",
            "description": "Learn some ways to use Core Image to transition between images.",
            "contentIdentifier": "io.github.WWDCPhotoFilters.imageTransitions",
            "contentVersion": "1.0",
            "url": "https://WWDCPhotoFilters.github.io/ImageTransitions/ImageTransitions.playgroundbook.zip",
            "publishedDate": "2018-05-18T12:00:00+00:00",
            "lastUpdatedDate": "2018-05-18T12:00:00+00:00",
            "thumbnailURL": "ImageTransitions/thumbnail.png",
            "bannerImageURL": "ImageTransitions/bannerImage.png",
            "additionalInformation": [
                {
                    "name": "Languages",
                    "value": "English"
                }
            ],
            "previewImageURLs": [
            "keypaths/preview-1.png"
            ]
        }
    ]
}

3.2.1 訂閱 Feeds JSON 數據分兩部分:訂閱 Feed 相關信息, document 即電子書相關信息

3.2.1.1 訂閱 Feed 相關信息

  • title :訂閱 Feed 的標題

    訂閱 Feed 的標題

  • publisherName :訂閱發布者的名稱

    訂閱發布者的名稱

  • feedIdentifier :訂閱 Feed 的唯一ID,一般直接用翻轉域名來標識

3.2.1.2 document:即電子書相關信息

  • title :電子書的標題

  • overviewSubtitle :電子書概覽標題

    電子書概覽標題

  • detailSubtitle :電子書更加具體的標題

    電子書更加具體的標題

  • description :電子書相關信息的一些描述

    電子書相關信息的一些描述

  • contentIdentifier : 電子書的唯一ID,一般是在 feedIdentifier 的基礎上拼接電子書的名稱

  • contentVersion :電子書發布版本號

  • thumbnailURL :電子書 icon

    電子書 icon

    電子書 icon2

  • bannerImageURL :電子書 banner,用于展示及推廣相關視覺圖

    電子書 banner

  • additionalInformation :額外信息,采用 Key-Value 的方式

  • previewImageURLs :電子書預覽圖

    電子書預覽圖

3.3. 托管你的訂閱源

  • 了解了訂閱 Feeds JSON 數據格式后,那么如何托管自己的訂閱源并分享給他人,我們可以把一系列 Playground 電子書的所有資源托管至第三方,創建自己的 JSON 文件,生成自己的訂閱鏈接,然后再通過 Safari 進行訂閱。
  • 下面我們以 GitHub Page 為例,來展示如果托管自己的訂閱源:
subscription_web_hosts
  1. 首先創建一個屬于自己的 GitHub Page


    image
  2. 然后在倉庫設置中配置好 GitHub Page。


    image
  3. 創建 Feeds JSON 文件
  4. 在倉庫中新建一個 index.html 或 README.md 文件,并把自己的訂閱鏈接放入其中。
  5. 都配置好后,我們的訂閱源已經托管至GitHub了,現在可以分享給其他小伙伴了,如何分享呢?
  1. 通過裝有 Swift Playgrounds 應用的 iPad,使用 Safari 訪問 GitHub Page,即 http://tingxins.com/Playground.github.io 。 點擊之前已配置好的鏈接進行訪問,即點擊 Subscribe,然后系統會自動調取 Swift Playgrounds 應用。
    image
  2. 直接在 Swift Playgrounds 應用內進行收到添加訂閱鏈接的方式進行訂閱。


    image
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容