javascriptnode.jssocket.ioswift2xcode7.1

Socket connectUser getting triggered multiple times in swift


I've downloaded a sample socket project from github https://github.com/appcoda/SocketIOChat

When I run the app it works fine, but the problem is that, where I exit an user and enter another name to connect, the connectUser method is getting triggered many times depending on number of time it connects. I just want it to connect only once. For example, below is piece of code from the sample above

func askForNickname() {
        let alertController = UIAlertController(title: "SocketChat", message: "Please enter a nickname:", preferredStyle: UIAlertControllerStyle.Alert)

        alertController.addTextFieldWithConfigurationHandler(nil)

        let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (action) -> Void in
            let textfield = alertController.textFields![0]
            if textfield.text?.characters.count == 0 {
                self.askForNickname()
            }
            else {
                self.nickname = textfield.text

                SocketIOManager.sharedInstance.connectToServerWithNickname(self.nickname, completionHandler: { (userList) -> Void in
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        if userList != nil {

                             print("USerlIst:\(userList)")
                            self.users = userList
                            self.tblUserList.reloadData()
                            self.tblUserList.hidden = false
                        }
                    })
                })
            }
        }

        alertController.addAction(OKAction)
        presentViewController(alertController, animated: true, completion: nil)
    }

Here everytime when I enter the chat with the user name, the connectToServerWithNickname method is getting triggered by the number of times I try to enter the name and prints the list multiple times. I've checked and in the above sample the socket is created as a singleton class and everytime it uses the same instance. What should I do to prevent this multiple call?


Solution

  • As I searched, it seems that each socket.on adds an handler so I fixed it by adding socket.off('event') before calling the on event.