1

I used to put GCDWebServer's start() and stop() in viewDidLoad and viewWillDisappear.

Now in SwiftUI, what is the equivalent place should I put them to? I try to put server init() into scene(_ scene: UIScene, willConnectTo, and server deinit() in sceneDidEnterBackground(_ scene:.

After launching the app, server is started successfully and when I push app to background, the server is stopped. That is worked fine. But when app returns to the foreground again, the server doesn't start again.

The Code:

class BrandViewController: UIViewController {
    let mockServer = GCDServer()
    let tableView = UITableView()
    private let products = ProductAPI.loadProducts()
    let searchController = UISearchController(searchResultsController: nil)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.searchController = searchController
        
        self.navigationController?.navigationBar.prefersLargeTitles = true
        navigationItem.title = "Search"
        
        view.backgroundColor = .white
        
        tableView.register(ProductCell.self, forCellReuseIdentifier: "productCell")
        tableView.dataSource = self
        tableView.delegate = self
        view.addSubview(tableView)
        
        // Start GCDWebServer
        mockServer.initWebServer()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        tableView.frame = view.bounds
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        mockServer.stopWebServer()
    }
}
Zhou Haibo
  • 1,681
  • 1
  • 12
  • 32

1 Answers1

0

If you destroy your server on sceneDidEnterBackground then the solution will be to move server creation (and, as I assume start) from scene(_ scene: UIScene, willConnectTo as you do now into sceneWillEnterForeground.

Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Thanks for the reply. I just did a quick test, this solution is worked! Also tried to put server init(), deinit() to ```onAppear``` and ```onDisappear``` in the entry SwiftUI page. It is worked too, so which is the better or as said correct way. For me, I don't want to put server operation code in the UI. – Zhou Haibo Jun 28 '20 at 08:29
  • onAppear/onDisappear might not always be called as would be expected (eg. during navigation, etc.), so it is not appropriate place for operate with server (in generic case). In some specific cases is up to you. – Asperi Jun 28 '20 at 08:40