我正在为我的 iOS 聊天应用程序使用 Socket.IO。聊天库调用socket.io-client-swift在 Swift 中,我可以设法使用桥接将它手动集成到我的 Objective-C 项目中。
我将“Source”文件夹从上面的库导入到我的 Xcode 中,并使用以下代码将 #import "MyProjectName-Swift.h"放入我的 ChatViewController 中:
//in viewDidLoad
NSURL* url = [[NSURL alloc] initWithString:@"http://localhost:3000/"];
SocketIOClient* socket = [[SocketIOClient alloc] initWithSocketURL:url options:@{@"log": @YES, @"forcePolling": @YES}];
[socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
NSLog(@"socket connected");
}];
[socket on:@"currentAmount" callback:^(NSArray* data, SocketAckEmitter* ack) {
double cur = [[data objectAtIndex:0] floatValue];
[socket emitWithAck:@"canUpdate" withItems:@[@(cur)]](0, ^(NSArray* data) {
[socket emit:@"update" withItems:@[@{@"amount": @(cur + 2.50)}]];
});
[ack with:@[@"Got your currentAmount, ", @"dude"]];
}];
[socket connect];
在 http://localhost:3000/ 的帮助下,我在本地使用 node.js(this tutorial)从中发送消息,我可以在我的 Xcode 控制台中同时看到它:
2016-05-13 14:59:20.345 CoreData_Chat[45303:372543] LOG SocketEnginePolling: Doing polling request
2016-05-13 14:59:24.033 CoreData_Chat[45303:373287] LOG SocketEnginePolling: Got polling response
2016-05-13 14:59:24.033 CoreData_Chat[45303:373287] LOG SocketEnginePolling: Doing polling request
2016-05-13 14:59:24.033 CoreData_Chat[45303:373285] LOG SocketEngine: Got message: 42["chat message","hii"]
2016-05-13 14:59:24.034 CoreData_Chat[45303:373285] LOG SocketIOClient: Should parse message: 2["chat message","hii"]
2016-05-13 14:59:24.034 CoreData_Chat[45303:373285] LOG SocketParser: Parsing 2["chat message","hii"]
2016-05-13 14:59:24.035 CoreData_Chat[45303:373285] LOG SocketParser: Decoded packet as: SocketPacket {type: 2; data: [chat message, hii]; id: -1; placeholders: -1; nsp: /}
2016-05-13 14:59:24.035 CoreData_Chat[45303:373285] LOG SocketIOClient: Handling event: chat message with data: (
hii)
那么,我如何发出此消息以显示在我的应用程序中和/或将消息发送到服务器。没有任何明确的教程解释这一点,尤其是在 Objective-C 中。谁能帮忙?谢谢。
最佳答案
NSMutableDictionary *messageServer = [[NSMutableDictionary alloc]init];
[messageServer setObject:@"bet" forKey:userActivity];
[messageServer setObject:@"0" forKey:betMoney];
SocketIOClient emit:EVENTNAME withItems:@[messageServer];
关于ios - 带有 Objective-C 客户端的 Socket.IO-Swift 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37203550/