PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 21, 2022

[FIXED] How do I use a socket on multiple viewcontrollers? swift-socket.io

 April 21, 2022     connection, sockets, swift     No comments   

Issue

i want create 1 connection And use it on multiple viewcontrollers without creating a new connection

this is my code for connection :

let manager = SocketManager(socketURL: URL(string: "https://mr-fast.liara.run")!, config: [.log(true), .compress])
var socket : SocketIOClient!
socket = manager.defaultSocket
socket.connect()

Solution

You can use Singleton pattern for this:

class SocketHandler {
    private init(){}
    static let shared = SocketHandler()

    private let manager = SocketManager(socketURL: URL(string: "https://mr-fast.liara.run")!, config: [.log(true), .compress])
    private(set) lazy var socket = manager.defaultSocket
}

Now you can access it from anywhere like:

SocketHandler.shared.socket.connect()

Note that this is just an example, you may want to use different names or use initializer to assign values to the variables.



Answered By - Mojtaba Hosseini
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing