This question already has an answer here:

I have an app which listens for a socket connection, and then uses DispatchSource.makeReadSource to read from the socket. This bit is working great:

let mySocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
// bind(...)
listen(newSocket, 1)

let clientSocket = accept(...)

let clientListener = DispatchSource.makeReadSource(
    fileDescriptor: clientSocket, 
    queue: DispatchQueue.main)
clientListener.setEventHandler {
    // Called when data is available, and I can read it without problem
}

My problem is while the dispatch source is waiting for data from the client, if I deploy my app (or stop my app) using Xcode, somehow the socket remains open and I cannot setup my socket again. When I call bind it returns -1

I have to restart my device for the socket to be released again

I've tried cleaning up my sockets when the app is closed, but I can't seem to detect when Xcode kills my app:

  • applicationWillTerminate is not called in my app delegate
  • deinit isn't called in any of my classes
  • none of the life cycle methods are called in my view controller

I'm not sure how the socket is remaining open as I would assume iOS would kill of all the resources when it killed the app

Is there a way to stop the dispatcher from holding on to the socket?

Related posts

Recent Viewed