swifter icon indicating copy to clipboard operation
swifter copied to clipboard

Network Connection Lost When Serving from SwiftUI View

Open jonobr1 opened this issue 4 years ago • 2 comments

I'm interested in serving a single page website as local files within my iOS app. I'm using swifter's shareFilesFromDirectory method to serve a number of HTML, JavaScript, CSS, images, and audio files successfully. However, I often (but not always) get a "Failed to load resource: The network connection was lost." in the WKWebView console on various assets.

Screen Shot 2020-12-22 at 9 16 41 AM

And this is the code for my view:

import WebKit
import SwiftUI
import Swifter

struct WebView: UIViewRepresentable {

  var url: String
  var server = HttpServer()
  var directories = [
    "styles", "third-party", "src", "images",
    "assets/A", "assets/B", "assets/C", "assets/D",
    "assets/E", "assets/F", "assets/G", "assets"
  ]

  func makeUIView(context: Context) -> WKWebView {

    let path = Bundle.main.bundlePath

    directories.forEach { (dir) in
      server["/\(dir)/:path"] = shareFilesFromDirectory("\(path)/www/\(dir)/")
    }

    server["/:path"] = shareFilesFromDirectory("\(path)/www")

    do {
      try server.start(8080)
    } catch {
      print("Failed to start local server.")
    }

    let view = WKWebView()
    let url = URL(string: "http://localhost:8080/index.html")!
    let request = URLRequest(url: url)

    view.allowsBackForwardNavigationGestures = false
    view.scrollView.contentInsetAdjustmentBehavior = .never
    //view.configuration = WKWebViewConfiguration
    view.load(request)

    return view

  }
  
  func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext<WebView>) {
    
  }

}

With an idea of what the project structure looks like here: Screen Shot 2020-12-22 at 9 17 18 AM

Lastly, from the Podfile it looks like I'm using 1.5.0. Is there a way to configure the server to handle more throughput? Or a more efficient way to serve the contents of a directory recursively?

jonobr1 avatar Dec 22 '20 14:12 jonobr1

Any luck with this? Having the same issue

fessehaye avatar Mar 18 '21 00:03 fessehaye

No, I ended up moving to https://github.com/swisspol/GCDWebServer

jonobr1 avatar Mar 18 '21 00:03 jonobr1