AutosoftDMS / SignalR-Swift

SignalR client library written in pure Swift
MIT License
60 stars 55 forks source link

Creating Global Hub and Using for whole Project. #19

Closed AravindSwamy09 closed 7 years ago

AravindSwamy09 commented 7 years ago

Hi I am developing a chat application by using SignalR-Swift. I want to create all the On and Invoke methods in SignalR into a Singleton class and use those methods for whole project. Invoke methods are working fine but On methods are not working for me and they are not giving any response when i called them in the controller file through delegate methods.

Please can you help me how to use these methods through out whole project.

vldalx commented 7 years ago

Hi take a look at Example

AravindSwamy09 commented 7 years ago

In controller class its working as in example but when i place that code in NSObject class for creating Signleton On methods are not responding.

vldalx commented 7 years ago

Can you provide a sample code?

AravindSwamy09 commented 7 years ago

I am creating a Signleton class like this

`class SignalRMethods: NSObject {

static let sharedInstance : SignalRMethods = {
    let instance = SignalRMethods()
    return instance
}()

var chatHub: HubProxy!
var connection: HubConnection!
var delegates : SignalRDelegates!

override init() {
    super.init()

}

func initializeMethods(url:String,scId:Int) {

    connection = HubConnection(withUrl: url)
    chatHub = connection.createHubProxy(hubName: "chatHub")

    _ = chatHub.on(eventName: "BroadCastMsg") { (response) in
        print(response as Any)
    }

    _ = chatHub.on(eventName: "RequestTyping") { (response) in
        print(response as Any)
        //            self.delegates.recievingMessage!(response: response as Any)
    }

    connection.started = { [weak self] in
        print("Connection ID: \(self!.connection.connectionId!)")
        //            self!.delegates.connected!(response: self!.connection.connectionId!)

    }

    connection.reconnecting = { [weak self] in
        print("Reconnecting")
        //            self!.delegates.reconnecting!(response: "")
    }

    connection.reconnected = { [weak self] in
        print("Reconnected")
        //            self!.delegates.reconnected!(response: self!.connection.connectionId!)
    }

    connection.closed = { [weak self] in
        print("Disconnected")
        //            self!.delegates.disconnected!(response: "")
    }

    connection.error = { error in
        //            self.delegates.errorMessage!(response: error as Any)
    }

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
        self.connection.start()
    }

}

func stopConnection() {
    connection.stop()
}

func sendMessage(params:[String:Any]) {

    chatHub.invoke(method: "MessageSend", withArgs: [name,msg])

}

}`

vldalx commented 7 years ago

I don't see any problem in your code. I've changed the example (see below) according to the way you want. Everything works fine. Double check the code in your app. Make sure the backend sends data that you expect.

import UIKit
import SignalRSwift

class ViewController: UIViewController {

    @IBOutlet weak var sendButton: UIButton!
    @IBOutlet weak var messageTextField: UITextField!
    @IBOutlet weak var chatTextView: UITextView!
    @IBOutlet weak var statusLabel: UILabel!
    @IBOutlet weak var startButton: UIBarButtonItem!

    var name: String!
    var connection: SignalRMethods!

    override func viewDidLoad() {
        super.viewDidLoad()

        let connection = SignalRMethods.sharedInstance
        connection.controller = self
        connection.initializeMethods(url: "http://swiftr.azurewebsites.net")
        connection.startConnection()
    }

    override func viewDidAppear(_ animated: Bool) {
        let alertController = UIAlertController(title: "Name", message: "Please enter your name", preferredStyle: .alert)

        let okAction = UIAlertAction(title: "OK", style: .default) { [weak self] _ in
            self?.name = alertController.textFields?.first?.text

            if let name = self?.name , name.isEmpty {
                self?.name = "Anonymous"
            }

            alertController.textFields?.first?.resignFirstResponder()
        }

        alertController.addTextField { textField in
            textField.placeholder = "Your Name"
        }

        alertController.addAction(okAction)
        present(alertController, animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func send(_ sender: AnyObject?) {
        if let message = messageTextField.text {
            SignalRMethods.sharedInstance.send(message: message, userName: name)
        }
        messageTextField.resignFirstResponder()
    }

    @IBAction func startStop(_ sender: AnyObject?) {
        if startButton.title == "Start" {
            SignalRMethods.sharedInstance.startConnection()
        } else {
            SignalRMethods.sharedInstance.stopConnection()
        }
    }
}

final class SignalRMethods: NSObject {

    static let sharedInstance = SignalRMethods()

    weak var controller: ViewController?

    var chatHub: HubProxy!
    var connection: HubConnection!

    private override init() {
        super.init()
    }

    func initializeMethods(url: String) {

        connection = HubConnection(withUrl: url)
        chatHub = connection.createHubProxy(hubName: "chatHub")

        _ = chatHub.on(eventName: "broadcastMessage") { (args) in
            if let controller = self.controller,
                let name = args[0] as? String,
                let message = args[1] as? String,
                let text = controller.chatTextView.text {
                controller.chatTextView.text = "\(text)\n\n\(name): \(message)"
            }
        }

        connection.started = { [unowned self] in
            guard let controller = self.controller else { return }
            controller.statusLabel.text = "Connected"
            controller.startButton.isEnabled = true
            controller.startButton.title = "Stop"
            controller.sendButton.isEnabled = true
        }

        connection.reconnecting = { [unowned self] in
            guard let controller = self.controller else { return }
            controller.statusLabel.text = "Reconnecting..."
        }

        connection.reconnected = { [unowned self] in
            guard let controller = self.controller else { return }
            controller.statusLabel.text = "Reconnected. Connection ID: \(self.connection.connectionId!)"
            controller.startButton.isEnabled = true
            controller.startButton.title = "Stop"
            controller.sendButton.isEnabled = true
        }

        connection.closed = { [unowned self] in
            guard let controller = self.controller else { return }
            controller.statusLabel.text = "Disconnected"
            controller.startButton.isEnabled = true
            controller.startButton.title = "Start"
            controller.sendButton.isEnabled = false
        }

        connection.connectionSlow = { print("Connection slow...") }

        connection.error = { [unowned self] error in
            let anError = error as NSError
            if anError.code == NSURLErrorTimedOut {
                self.connection.start()
            }
        }

    }

    func stopConnection() {
        connection.stop()
    }

    func startConnection() {
        connection.start()
    }

    func send(message: String, userName name: String) {
        chatHub.invoke(method: "send", withArgs: [name, message])
    }
}
AravindSwamy09 commented 7 years ago

Thanks for the help it helped me a lot thank you