0

I have the following code, which is basically a template of a blank app that Xcode created, and I'm using a library called Swifter (renamed here Swifter2 because of name conflict) where Im trying to start a local http server on my iPhone device. This was my attempt to do so:

//
//  ContentView.swift
//  HTTPServerIOSApp

import SwiftUI
import Swifter2

func startServer()  {
    do {
        let server = HttpServer()
        server["/"] = { request in
            return HttpResponse.ok(.text("<html string>"))
        }
        try server.start(9081)
        
    } catch {
        print("Server start error: \(error)")
    }
}





struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .padding() 
       Button("Start Server!",
      action: {
          startServer()
      })

    }
}


struct ContentView_Previews: PreviewProvider {
    
   
    static var previews: some View {
        ContentView()
        
    }
    
  
}

The reason why Im using a button to call the function is because apparently (Im very new to Swift so this isn't clear to me) I couldn't just call the function in the ContentView. Now the problem is that when I call the function it seems to work but I can't find anything on the localhost:9081, it keeps saying the page doesn't exist. Is it because the application doesn't run in background and thus doesn't keep the server alive ?

MM1
  • 912
  • 1
  • 10
  • 28
  • Does it say "Could not open the page because it could not connect to the server" or is it a literal page not found error? If the former, you should check the application logs. Maybe, instead of printing the error, display it in your content view. – JeremyP Aug 10 '22 at 14:51
  • Yes it exactly says cannot open the page because it could not connect to the server, do you know how can I display the error ? Because even when printing I get nothing in the console and it seems everything is woking fine – MM1 Aug 10 '22 at 14:53
  • The server is probably starting then by the sandbox is preventing it from connecting anywhere. SwatGuard's answer, though a bit brief is going in the right direction. – JeremyP Aug 10 '22 at 15:41
  • Of course it doesn’t run in the background. https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle – cora Aug 10 '22 at 15:41
  • @cora Oh yes. That is a good point. When you switch to the browser, your app will end up not running. – JeremyP Aug 10 '22 at 15:58
  • So do you have a way to make this server run on iOS, from what Ive seen running app on background indefinitely is not possible. Do you have a way that might perhaps help me achieve run my web server on the device ? Thank you! – MM1 Aug 10 '22 at 17:25

0 Answers0