我试图使GCDWebServer显示静态内容。我有代码
import UIKit
import Foundation
class ViewController: UIViewController {
var webServer:GCDWebServer?
let urlpath = NSBundle.mainBundle().pathForResource("index", ofType: "html", inDirectory: "www")
override func viewDidLoad() {
super.viewDidLoad()
initWebServer()
}
func initWebServer() {
webServer = GCDWebServer()
webServer!.addGETHandlerForBasePath("/", directoryPath: urlpath, indexFilename: "index.html", cacheAge: 3600, allowRangeRequests: true)
webServer!.startWithPort(8080, bonjourName: "GCD Web Server")
print("Visit (webServer!.serverURL) in your web browser")
}
}
我也有文件夹www在我的Xcode项目的根目录
服务器启动时,在控制台中显示服务器地址为192.168.1.2:8080。但是当我尝试在浏览器中打开该url时,我没有看到index.html,黑屏和控制台404。
我做错了什么
您需要将目录的fullpath传递给directoryPath,请查看下面我的代码示例:
private func loadDefaultIndexFile() {
let mainBundle = NSBundle.mainBundle()
let folderPath = mainBundle.pathForResource("www", ofType: nil)
print("HTML base folder Path: (folderPath)")
self.gcdWebServer.addGETHandlerForBasePath("/", directoryPath: folderPath, indexFilename: "index.html", cacheAge: 0, allowRangeRequests: true)
self.gcdWebServer.startWithPort(8080, bonjourName: nil)
self.webView.loadRequest(NSURLRequest(URL: self.gcdWebServer.serverURL))
}
希望有所帮助
您需要在初始化时将路径传递给要服务的目录,而不是将索引文件传递给GCDWebServer。