问题
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