GCDWebServer 的 Swift 包

基于 swisspol/GCDWebServer

GCDWebServer 是一个基于 GCD 的现代轻量级 HTTP 1.1 服务器,旨在嵌入到 iOS、macOS 和 tvOS 应用程序中。

使用方法

  1. 打开“文件” > “添加包”
  2. 将 URL 粘贴到右上角的搜索框 https://github.com/yene/GCDWebServer
  3. 扩展你的项目,例如在你的 didFinishLaunchingWithOptions 中启动服务器
import UIKit
import GCDWebServer

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
  let webServer = GCDWebServer()

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    webServer.addDefaultHandler(forMethod: "GET", request: GCDWebServerRequest.self, processBlock: {request in
      return GCDWebServerDataResponse(html:"<html><body><p>Hello World</p></body></html>")
    })
    webServer.start(withPort: 8080, bonjourName: "GCD Web Server")
    print("Visit \(webServer.serverURL) in your web browser")
    return true
  }
  // ...
}

提供静态目录

将包含你的 html 文件的文件夹拖到 Xcode 项目中。在此示例中,该文件夹名为 dist,并且内部有一个 index.html 文件。

在开发过程中,请务必禁用缓存。

import UIKit
import GCDWebServer

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
	let webServer = GCDWebServer()

	func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

		let subdir = Bundle.main.resourceURL!.appendingPathComponent("dist").path
		webServer.addGETHandler(forBasePath: "/", directoryPath: subdir, indexFilename: "index.html", cacheAge: 3600, allowRangeRequests: true)
		webServer.start(withPort: 8080, bonjourName: "GCD Web Server")
		print("Visit \(webServer.serverURL) in your web browser")
		return true
	}
  // ...
}