GCDWebServer 是一个基于 GCD 的现代轻量级 HTTP 1.1 服务器,旨在嵌入到 iOS、macOS 和 tvOS 应用程序中。
https://github.com/yene/GCDWebServer
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
}
// ...
}