我在我的iOS聊天应用程序中使用Socket.IO。名为socket.io-client-swift的聊天库位于Swift中,我可以设法使用桥接手动将其集成到我的Objective-C项目中。
我导入了'来源'从库上面的文件夹到我的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/的帮助下在本地(this tutorial)使用node.js来发送消息,我可以在我的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中。有人可以帮忙吗?谢谢。
答案 0 :(得分:2)
NSMutableDictionary *messageServer = [[NSMutableDictionary alloc]init];
[messageServer setObject:@"bet" forKey:userActivity];
[messageServer setObject:@"0" forKey:betMoney];
SocketIOClient emit:EVENTNAME withItems:@[messageServer];