httpswift / swifter

Tiny http server engine written in Swift programming language.
BSD 3-Clause "New" or "Revised" License
3.89k stars 540 forks source link

How to load Html File in WKWebView or SFSafariVC ? #371

Open theRealGupta opened 5 years ago

theRealGupta commented 5 years ago

How to load HTML by string?

let server = HttpServer()
server[path] = { request in
    return HttpResponse.ok(.text("<html string>"))
}
server.start()

This code is mention in your Doc file.

Que 1: What is server[path] ? Means Path = ??? in place of path what path i will provide? Que 2: After loading Html file in using HttpHandlers.directory(NSBundle.mainBundle().resourcePath! + "/www") how i will display in our WKWebView or SFSafariVC ? what will be url for that?

Vkt0r commented 5 years ago

Uhmm 🤔 I think we need to add more docs to the repository to explain the different uses of the library. I'm going to create a new issue to keep track of missing docs.

For now @anupgupta-arg I'm going to explain to you each one of your cases in the best I can for now 😀:

What is server[path]?

In the example of the README is where you define your routes for example:

server["/hello"] = { request in
    return HttpResponse.ok(.text("<html string>"))
}

By default, the server is going to run in localhost:8080 or any other port you specify when you started it. So the above definition of the route hello means when you post localhost:8080/hello in any browser including your Safari in your Mac or Simulator the response would be the specified in this case the <html string>.

After loading the HTML file using HttpHandlers.directory(NSBundle.mainBundle().resourcePath! + "/www") how I will display in our WKWebView or SFSafariVC

So let's say you want to display some HTML file as the response for a specific request and for the sake of simplicity let's use the same route as before /hello. So we want the server emits the HTML file we load from the Bundle so something like this would work:

server["/hello"] = { request in
    let stringFile = // load your file here as a String file 
    return HttpResponse.ok(.text(stringFile))
}

But we have some public functions to handle some cases too:

https://github.com/httpswift/swifter/blob/b33295680aea4fae0d88f07024da35b4d9f33ca2/Sources/Files.swift#L10

A very good file with examples can be found in the https://github.com/httpswift/swifter/blob/stable/Sources/DemoServer.swift

I hope this can help you!