Два пути для разных локальных ресурсов в GCDWebServer

Мне нужно инициализировать GCDWebServer двумя путями для разных локальных ресурсов (игры HTML5).

Теперь я могу создать путь только для одного ресурса с помощью addGETHandler. Этот обработчик можно использовать один раз, если вы будете использовать его снова, старый обработчик будет удален, а новый займет его место.

Это мой код:

let firstGameFolderPath = Bundle.main.path(forResource: "game1", ofType: nil)
ServerService.gcdWebServer.addGETHandler(forBasePath: "/", directoryPath: firstGameFolderPath!, indexFilename: "index.html", cacheAge: 0, allowRangeRequests: true)
ServerService.gcdWebServer.start(withPort: 8080, bonjourName: "GCD Web Server")

Если у кого-то есть идеи, как решить эту задачу, было бы неплохо.

P.S. У меня была идея создать 2 сервера с разными портами, но это слишком дорого.

Контроллер, где все происходит (метод didSelectRowAt):

import UIKit

class MenuViewController: UITableViewController, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.tableFooterView = UIView()
        self.navigationController?.delegate = self
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let menuCell = tableView.dequeueReusableCell(withIdentifier: "MenuCell") as? MenuTableViewCell
        switch indexPath.row {
        case 0:
            menuCell?.updateCell(title: "Главная")
        case 1:
            menuCell?.updateCell(title: "Первая игра")
        case 2:
            menuCell?.updateCell(title: "Вторая игра")
        default:
            break
        }
        return menuCell!
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let menuCell = tableView.cellForRow(at: indexPath) as! MenuTableViewCell

        switch indexPath.row {
        case 0:
            self.view.window!.rootViewController?.dismiss(animated: true, completion: nil)
        case 1:
            menuCell.activityIndicator.startAnimating()
            let firstGameFolderPath = Bundle.main.path(forResource: "game1", ofType: nil)
            ServerService.gcdWebServer.addGETHandler(forBasePath: "/", directoryPath: firstGameFolderPath!, indexFilename: "index.html", cacheAge: 0, allowRangeRequests: true)
            ServerService.gcdWebServer.start(withPort: 8080, bonjourName: "GCD Web Server")
            self.perform(#selector(showGameVC), with: nil, afterDelay: 1) //Delay for launching WebServer
        case 2:
            menuCell.activityIndicator.startAnimating()
            let secondGameFolderPath = Bundle.main.path(forResource: "game2", ofType: nil)
            ServerService.gcdWebServer.addGETHandler(forBasePath: "/", directoryPath: secondGameFolderPath!, indexFilename: "index.html", cacheAge: 0, allowRangeRequests: true)
            ServerService.gcdWebServer.start(withPort: 8080, bonjourName: "GCD Web Server")
            self.perform(#selector(showGameVC), with: nil, afterDelay: 1) //Delay for launching WebServer
        default:
            break
        }

        tableView.deselectRow(at: indexPath, animated: true)
    }

    @objc func showGameVC() {
        let gameViewController = self.storyboard?.instantiateViewController(withIdentifier: "GameVC") as! GameViewController
        self.navigationController?.pushViewController(gameViewController, animated: true)
    }
} 

Ссылка на репозиторий


person MrTishman    schedule 26.01.2019    source источник


Ответы (2)


Вы можете попробовать дать им разные базовые пути.

let firstGameFolderPath = Bundle.main.path(forResource: "game1", ofType: nil)
ServerService.gcdWebServer.addGETHandler(forBasePath: "/game1", directoryPath: firstGameFolderPath!, indexFilename: "index.html", cacheAge: 0, allowRangeRequests: true)
ServerService.gcdWebServer.start(withPort: 8080, bonjourName: "GCD Web Server")

let secondGameFolderPath = Bundle.main.path(forResource: "game2", ofType: nil)
ServerService.gcdWebServer.addGETHandler(forBasePath: "/game2", directoryPath: secondGameFolderPath!, indexFilename: "index.html", cacheAge: 0, allowRangeRequests: true)
ServerService.gcdWebServer.start(withPort: 8080, bonjourName: "GCD Web Server")

а затем, когда вам нужно загрузить игру, вы можете добавить ту же игру1 или игру2 в URL-адрес почтового запроса.

как это

let game1Request = URLRequest(url: URL(string:"{YourGCDWebServerURL}/game1")!)
let game2Request = URLRequest(url: URL(string:"{YourGCDWebServerURL}/game2")!)
person nishith Singh    schedule 26.01.2019
comment
Да, я это сделал, но вот БОЛЬШАЯ проблема) URL-адрес сервера доступен через 2-3 секунды после запуска сервера. Это не очень удобно, когда переключаешься между ресурсами, и приходится выставлять задержку. Я добавлю свой быстрый файл в тему для лучшего понимания. - person MrTishman; 26.01.2019
comment
Я имею в виду: лучше запустить сервер с 2 ресурсами (например) в viewDidAppear, и когда UIView загрузится, у нас будет работающий сервер с serverURL. - person MrTishman; 26.01.2019
comment
Ваш файл кода поможет. Если вариант использования вашего приложения позволяет, вы также можете попробовать загрузить GCDWebServer при загрузке вашего приложения. Скажите в приложенииDidFinishLaunching. Таким образом, вы будете готовы, когда появится ваше представление. - person nishith Singh; 26.01.2019

Вы можете добавить столько обработчиков, сколько хотите, к GCDWebServer, поэтому просто добавьте еще один с другим путем к каталогу И другим базовым путем:

ServerService.gcdWebServer.addGETHandler(forBasePath: "/assets1/", directoryPath: firstGameFolderPath!, indexFilename: "index.html", cacheAge: 0, allowRangeRequests: true)
ServerService.gcdWebServer.addGETHandler(forBasePath: "/assets2/", directoryPath: secondGameFolderPath!, indexFilename: "index.html", cacheAge: 0, allowRangeRequests: true)

Этот обработчик можно использовать один раз, если вы будете использовать его снова, старый обработчик будет удален, а новый займет его место.

Это неправда, обработчики никогда не удаляются, пока вы не вызовете -removeAllHandlers — см. https://github.com/swisspol/GCDWebServer/blob/master/GCDWebServer/Core/GCDWebServer.m.

person Pol    schedule 21.05.2019