swisspol / GCDWebServer

The #1 HTTP server for iOS, macOS & tvOS (also includes web based uploader & WebDAV server)
Other
6.51k stars 1.25k forks source link

Request to GCDWebServer Hanging Forever #179

Closed eitan1990 closed 9 years ago

eitan1990 commented 9 years ago

I'm using GCDWebServer to serve an html from my iPhone app to Safari on the same device. I start the server with a default handler for returning that html on every GET response and then I open the url to my webserver using Safari:

NSURL *serverUrl = [NSURL URLWithString: [NSString stringWithFormat: @"http://localhost:%lu", (unsigned long)_webServer.port]];
[[UIApplication sharedApplication] openURL:serverUrl];

The app is sent to the background, and Safari is opened to localhost.

Most of the times this works perfectly and my html is served instantly, but sometimes Safari loads forever until it gives up and tells me that the page was not found.

Here is the code where I start the server:

_webServer = [[GCDWebServer alloc] init];
[_webServer addDefaultHandlerForMethod:@"GET"
                         requestClass:[GCDWebServerRequest class]
                         processBlock:^GCDWebServerResponse *(GCDWebServerRequest *request) {
                             return [GCDWebServerDataResponse responseWithHTML:myHtml];
                         }];

NSDictionary *options = @{
  GCDWebServerOption_Port: @([self randomPortNumber]) ,
  GCDWebServerOption_AutomaticallySuspendInBackground: @NO
};
NSError *error;
BOOL serverStarted = [_webServer startWithOptions:options error:&error];

Any ideas why this is happening and/or how to solve this? Thanks!

swisspol commented 9 years ago

You pretty much can't run a web server in the background on iOS: see https://github.com/swisspol/GCDWebServer#gcdwebserver--background-mode-for-ios-apps.

eitan1990 commented 9 years ago

But I set the GCDWebServerOption_AutomaticallySuspendInBackground option to @NO. According to the link you sent, this doesn't stop the server.

And if I start a connection to the local server before I background the app, will that keep the server alive in the background? Is there some other way to do this?

swisspol commented 9 years ago

It doesn't stop the server automatically anymore so you have to eventually do it by hand. iOS will freeze your app no matter what, at most after 10 minutes or anytime earlier, so at most your web server can run a few minutes in the background. And if you app is frozen, the listening socket doesn't respond, letting to Safari connections hanging and such.

Review the README and linked Apple tech notes carefully.