How to serve a single page application in a Swift iOS app?

1.4k views Asked by At

I have a Swift project with a webview that is serving files from a local folder vai GCDwebserver, however the website is designed as a single page application, is there any way I can rewrite all url requests to index.html?

I'm currently using GCDwebserver but I'm willing to change servers to get the SPA to load in the webview.

With nginx I'd do somthing like

server {
     listen 8080;
     listen [::] 8080;
     root /root/bundled;
 location / {
      try_files $uri $uri/ /index.html;
 }
}

How do I get the same rewrite effect on a webview in osx?

2

There are 2 answers

0
Pol On

Simply use a default handler to catch all GET request:

- (void)addDefaultHandlerForMethod:(NSString*)method requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block;

Or a regex one if you want to do more fancy matching:

- (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block

Or even go all the way to a match block:

- (void)addHandlerWithMatchBlock:(GCDWebServerMatchBlock)matchBlock processBlock:(GCDWebServerProcessBlock)processBlock;
0
RichardMoult On

I must admit I've never used GCDWebserver, but if you have any requirement in an iOS app to redirect a url you can use NSURLProtocol. You can read more about it here https://www.raywenderlich.com/76735/using-nsurlprotocol-swift. Once you've read the link you basically need to use the method canonicalRequestForRequest to capture the current request and return a new one. Hope that helps.