Swift上的GCDWebServer静态网站

时间:2015-10-04 14:19:15

标签: swift gcdwebserver

我试图让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")
}
}

我的Xcode项目根目录中也有文件夹www

当服务器启动时,它会在控制台中显示服务器地址为192.168.1.2:8080。但是当我尝试在浏览器中打开该网址时,我在控制台中看不到index.html,黑屏和404.

我做错了什么?

2 个答案:

答案 0 :(得分:5)

您需要将目录的完整路径传递给 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))
}

希望有所帮助

答案 1 :(得分:0)

您需要将路径传递给目录,以便在初始化时不将索引文件提供给GCDWebServer。