GCDWebServer - статические файлы из документов

Я использую GCDWebServer для создания HTTP-сервера на своем устройстве. Фактический контент для веб-страницы помещается в папку «Документы» моего приложения. Содержимое содержит файл HTML с указанными файлами css и png. Проблема в том, что файлы css и png недоступны/используются с сервера (я вижу только текстовое содержимое HTML).

Соответствующий код:

self.server = [[GCDWebServer alloc] init];

NSString *documents = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] absoluteString];
documents = [documents stringByAppendingPathComponent:@"MyWebsite"];

[self.server addGETHandlerForBasePath:@"/" directoryPath:documents indexFilename:nil cacheAge:0 allowRangeRequests:YES];

__weak typeof(self) weakSelf = self;

[_server addDefaultHandlerForMethod:@"GET" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse *(GCDWebServerRequest *request) {

        if ([[request path] isEqualToString:@"/status"]) {

            return [GCDWebServerDataResponse responseWithText:@"RUNNING"];
        }

        else if ([[request path] isEqualToString:@"/"]) {

            NSString *filePath = [documents stringByAppendingPathComponent:@"mypage.html"];
            NSString *html = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
            return [GCDWebServerDataResponse responseWithHTML:html];

        }    

    return nil;

}];

[self.server startWithOptions:@{GCDWebServerOption_Port: @(80)} error:&error];

Спасибо!


person Sebastian    schedule 22.06.2015    source источник


Ответы (1)


Я нашел решение:

Добавление обработчика с server addGETHandlerForBasePath, а затем server addDefaultHandlerForMethod: кажется неправильным.

Мне пришлось внести следующие изменения:

добавитьGETHandlerForBasePath:

// using `absoluteString` is adding "file://" in front of the path. This seems to be wrong. The following code will create a correct path string.
const char *path = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] fileSystemRepresentation];
NSString *documents = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:path length:strlen(path)];

// full path to the HTML file
NSString *htmlFile = [documents stringByAppendingPathComponent:...];

// "directoryPath" has to be the path to folder with the (main) HTML, not the subfolder of the files. I have a separate folder only for the static files. GCDWebServer will search for the files by it's self - recursive.
[self.server addGETHandlerForBasePath:@"/" directoryPath: documents indexFilename:htmlFile cacheAge:0 allowRangeRequests:YES];

добавить другой обработчик GET:

Я должен использовать метод addHandler....

[self.server addHandlerForMethod:@"GET" path:@"/status" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse *(GCDWebServerRequest *request) {

    // ... same implementation as in the question
}];
person Sebastian    schedule 22.06.2015