如何在Swift 4中连接Socket [英] How to connect Socket in Swift 4
问题描述
我想将我的应用程序连接到套接字,这里是代码:-
I want to connect my app to the socket here is the code :-
import UIKit
import SocketIO
class SocketIOManager: NSObject {
static let manager = SocketManager(socketURL: URL(string: "myURL")!)
static let socket = manager.defaultSocket
class func connectSocket() {
let token = UserDefaults.standard.getAccessToken()
self.manager.config = SocketIOClientConfiguration(
arrayLiteral: .connectParams(["token": token]), .secure(true) // problem is here in passing token value
)
socket.connect()
}
class func receiveMsg() {
socket.on("new message here") { (dataArray, ack) in
print(dataArray.count)
}
}
}
我创建了一个新类SocketIOManager.swift,并在视图控制器中调用了函数
I created a new class SocketIOManager.swift and I invoke my function in view controller
SocketIOManager.connectSocket()
并且我没有使用localhost url,但是我的应用程序仍未连接到套接字,我想我遵循了,我还将在Info.plist中添加应用传输安全性.有什么帮助吗?问题是当我传递令牌值时,它将给我错误,否则它将正常工作.使用套接字时是否需要传递令牌?
and I am not using the localhost url but still my app is not connected to the socket I think I followed this and I also add App Transport Security in info.plist. Any help? The problem is when I am passing the token value it gives me error otherwise it is working properly. Should I need to pass token when using socket?
推荐答案
您应该像这样在您的SocketIOManager
类中创建一个共享属性:
You should make a shared property in your SocketIOManager
class like this:
static let shared = SocketIOManager()
,然后像这样创建init()
:
var socket: SocketIOClient!
// defaultNamespaceSocket and swiftSocket both share a single connection to the server
let manager = SocketManager(socketURL: URL(string: "http://localhost:3000")!, config: [.log(true), .compress])
override init() {
super.init()
socket = manager.defaultSocket
}
最后编写这样的方法:
func connectSocket() {
let token = UserDefaults.standard.getAccessToken()
self.manager.config = SocketIOClientConfiguration(
arrayLiteral: .connectParams(["token": token]), .secure(true)
)
socket.connect()
}
func receiveMsg() {
socket.on("new message here") { (dataArray, ack) in
print(dataArray.count)
}
}
并像这样调用您的方法:
and call your method like this:
SocketIOManager.shared.connectSocket()
要点是,您应该在viewController中强烈引用manager属性,而static let shared = SocketIOManager()
则应为您执行此操作!
The point is that you should make a strong reference to manager property in your viewController and static let shared = SocketIOManager()
you do this for you!
这篇关于如何在Swift 4中连接Socket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!