GCDWebServer static website on Swift

依然范特西╮ 提交于 2021-02-07 08:40:24

问题


I'm trying to make GCDWebServer show static content. I have code

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")
}
}

also i have folder www in root of my Xcode project

when server starts, it shows me in console that server address is 192.168.1.2:8080. But when i try to open that url in browser i don't see index.html, black screen and 404 in console.

What am I doing wrong ?


回答1:


You will need to pass fullpath of your directory to directoryPath, please have a look at my code example below:

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))
}

Hope it helps




回答2:


You need to pass the path to the directory to serve not the index file to GCDWebServer on initialization.



来源:https://stackoverflow.com/questions/32934446/gcdwebserver-static-website-on-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!