I found following libraries to start a server locally.
For instance, I'm using swifter. It does compile for iOS.
I also added code to start a local server as follows.
class ViewController: UIViewController {
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let server = HttpServer()
server["/hello"] = { .ok(.htmlBody("You asked for \($0)")) }
let semaphore = DispatchSemaphore(value: 0)
do {
try server.start(9080, forceIPv4: true)
print("Server has started ( port = \(try server.port()) ). Try to connect now...")
let config = WKWebViewConfiguration()
webView = WKWebView(frame: self.view.bounds, configuration: config)
/////////////////////////////
// What should be url here to point to local server?
webView.load(URLRequest(url: URL(string: "")!))
/////////////////////////////
view = webView
semaphore.wait()
} catch {
print("Server start error: \(error)")
semaphore.signal()
}
}
}
Also, If I submit it to apple, is there any possibility of rejection because of starting a local server?
2 Answers
Can you elaborate on what you are trying to achieve by starting an HTTP server in-process?
If you need control over the way that responses are made, I would recommend looking at registering a custom URL protocol handler with WKWebViewConfiguration.setURLSchemeHandler(_:forURLScheme:). Then, ask the WKWebView to load a resource from that custom URL scheme, and your handler (that conforms to WKURLSchemeHandler) will get called, and you can construct a URLResponse however you'd like.
I tried Telegraph
Step 1. Open Podfile & add a dependency - pod 'Telegraph'
Step 2. Open AppDelegate.swift & put code as follows.
// Serve the Server from Build folder
let demoBundleURL = Bundle.main.url(forResource: "webApp", withExtension: nil)!
// and handle those requests at Path
serverHTTP.serveDirectory(demoBundleURL, "/webApp")
// Setting Custom Router - OPTIONAL
serverHTTP.httpConfig.requestHandlers.insert(DRHTTPMiddleWare(), at: 0)
// Start Server
try? serverHTTP.start(port: 9000, interface: "localhost")
Step 3. In ViewController.swift, put code as follows.
func loadWebView() {
guard let url = URL(string: "") else { return }
webView = WKWebView(
frame: self.view.bounds,
configuration: WKWebViewConfiguration()
)
webView.load(URLRequest(url: url))
view = webView
}