You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 4中Socket连接实现及token传递问题求助

Fixing Token Delivery & Correct Socket.IO Connection in Swift 4

Got it, let's sort out that token issue and cover the proper way to connect Socket.IO in Swift 4. Here's what's going wrong in your original code, plus a complete corrected implementation:

What's the Problem?

Your current code initializes SocketManager and its default socket first, then tries to update the manager's config afterward. But once the socket is created from the manager, it locks in the initial configuration—any later changes to manager.config won't affect the existing socket instance. That's why your token isn't being passed during the connection.

Corrected Implementation

Here's a revised, robust version of your SocketIOManager that fixes the token issue and follows best practices:

import UIKit
import SocketIO

class SocketIOManager: NSObject {
    // Use an instance singleton instead of static class properties for better lifecycle control
    static let shared = SocketIOManager()
    
    private var manager: SocketManager!
    private var socket: SocketIOClient!
    
    // Private init to enforce singleton pattern
    private override init() {
        super.init()
    }
    
    func connectSocket() {
        // First, make sure we have a valid token
        guard let token = UserDefaults.standard.getAccessToken(), !token.isEmpty else {
            print("Error: No valid access token found in UserDefaults")
            return
        }
        
        // Build the configuration FIRST, including your token and secure flag
        let socketConfig = SocketIOClientConfiguration(arrayLiteral:
            .connectParams(["token": token]),
            .secure(true),
            .log(true, logLevel: .debug) // Enable debug logs to verify token delivery
        )
        
        // Initialize the manager with the correct config, then get the socket
        manager = SocketManager(socketURL: URL(string: "myURL")!, config: socketConfig)
        socket = manager.defaultSocket
        
        // Listen for connection events to confirm success
        socket.on(clientEvent: .connect) { [weak self] _, _ in
            guard let self = self else { return }
            print("✅ Socket connected successfully with token: \(token)")
            // Add your event listeners here (e.g., socket.on("some-event") { ... })
        }
        
        socket.on(clientEvent: .error) { data, _ in
            print("❌ Socket connection error: \(data)")
        }
        
        socket.on(clientEvent: .disconnect) { _, _ in
            print("🔌 Socket disconnected")
        }
        
        // Finally, initiate the connection
        socket.connect()
    }
    
    func disconnectSocket() {
        socket?.disconnect()
        // Clean up references to avoid memory leaks
        manager = nil
        socket = nil
    }
    
    // Add your custom Socket event handlers here
    // Example:
    // func listenForChatMessages() {
    //     socket?.on("new-message") { data, ack in
    //         // Handle incoming message
    //     }
    // }
}

Key Improvements & Best Practices

  • Order of Operations: We create the configuration before initializing the SocketManager, so the token is included from the start.
  • Singleton Pattern: Using an instance singleton (static let shared) gives you better control over the socket's lifecycle compared to static class properties.
  • Token Validation: We check for a valid token before attempting to connect, preventing useless connection attempts.
  • Debug Logs: The .log(true) flag lets you see exactly what's being sent in the connection request—you can verify your token is included by checking the console output.
  • Connection State Listening: Adding handlers for .connect, .error, and .disconnect helps you debug issues and react to state changes in your app.
  • Memory Management: We clean up manager and socket references when disconnecting to avoid memory leaks.

How to Use It

Call the connect method from your view controller or app delegate like this:

SocketIOManager.shared.connectSocket()

And don't forget to disconnect when you're done (e.g., in viewWillDisappear or when the user logs out):

SocketIOManager.shared.disconnectSocket()

内容的提问来源于stack exchange,提问作者viper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:27:31