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.
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()
}
}
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
.