Alexey K
Alexey K

Reputation: 6723

GCDWebServer static website on Swift

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 ?

Upvotes: 5

Views: 3279

Answers (2)

Jack Vo
Jack Vo

Reputation: 319

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

Upvotes: 5

Pol
Pol

Reputation: 4008

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

Upvotes: 0

Related Questions