我希望有人可以帮助我。我试图将SIOSocket与Swift项目一起使用。
我正在使用https://github.com/MegaBits/SIOSocket/issues/30上的示例,这似乎有效,但我希望能够将socket
声明为var
,就像self
上的Objective-C项目示例一样3}}。所以我可以在代码中使用else来调用emit。
我假设我不理解Obj-C块和Swift闭包基础知识以及var
的使用或者需要将 @property SIOSocket *socket;
[SIOSocket socketWithHost: @"http://localhost:3000" response: ^(SIOSocket *socket)
{
self.socket = socket; //I Want to do this in swift
__weak typeof(self) weakSelf = self;
self.socket.onConnect = ^()
{
weakSelf.socketIsConnected = YES;
[weakSelf mapView: weakSelf.mapView didUpdateUserLocation: weakSelf.mapView.userLocation];
};
[self.socket on: @"join" callback: ^(SIOParameterArray *args)
{
[weakSelf mapView: weakSelf.mapView didUpdateUserLocation: weakSelf.mapView.userLocation];
}];
[self.socket on: @"update" callback: ^(SIOParameterArray *args)
{
NSString *pinData = [args firstObject];
声明为块,但似乎无法理解它。任何帮助都感激不尽。
https://github.com/MegaBits/WorldPin
Objective-C代码:
private func connectToHost() {
SIOSocket.socketWithHost(host, reconnectAutomatically: true, attemptLimit: 0, withDelay: 1, maximumDelay: 5, timeout: 20, response: {
socket in
self.socket = socket // This gives me a use of unresolved identifier self error
socket.onConnect = {
println("Connected to \(host)")
socket.emit("add user", args: [username])
}
socket.on("login", callback: {(AnyObject data) -> Void in
println(["login": data])
socket.emit("new message", args: [message])
})
socket.onDisconnect = {
println("Disconnected from \(host)")
}
})
}
等等......
Swift Code:
{{1}}
答案 0 :(得分:0)
尝试将其更改为:
SIOSocket.socketWithHost(host, reconnectAutomatically: true, attemptLimit: 0, withDelay: 1, maximumDelay: 5, timeout: 20, response: {(socket: SIOSocket) in
self.socket = socket // This gives me a use of unresolved identifier self error
//...
})
我将socket in
更改为(socket: SIOSocket) in
答案 1 :(得分:0)
您的代码应该有效,请确保您拥有所有正确的类型和可选类型,通过read-write
而不是var
来确定套接字是let
变量。< / p>
尝试使用let response: (SIOSocket) -> Void = {...}
。