试图以特定格式发送一串单词

时间:2013-09-11 00:23:08

标签: ios objective-c sockets dictionary

现在我正在处理目标-c上的socket.io,我正在处理发送事件请求。我正在使用pkyeck socket.io api并发送一个事件,他们将它设置为你将args值放在一个字典中,在sentevent函数中处理该字典,并使用您发送的变量字典并将其与args键。因此,如果我遵循该模式,我发送到socket.io服务器的事件看起来像这样。

{"args":[{"username":"yeah", "id":"2"}],"name":"login"}

但是,为了让我的服务器正确处理socket.io调用,调用需要看起来像这样。

{"args":["yeah","2"],"name":"login"}

但是我无法以这种方式发送变量,因此字典可以像这样设置它。如果我使用NSArray,请求就会这样发送。

{"args":[["yeah","2"]}],"name":"login"}

如果我发送附加字符串,它看起来像这样。

{"args":[{"'yeah','2'"}],"name":"login"}

这是我到目前为止所做的事情

- (void) socketIO:(SocketIO *)socket onMessage:(NSString *)status{
NSLog(@"Current status %@", status);
if([status isEqualToString:@"ready"]){
    SocketIOCallback cb = ^(id argsData) {
        NSDictionary *response = argsData;
        // do something with response
        NSLog(@"ack arrived: %@", response);

        // test forced disconnect
        //[socketIO disconnectForced];
    };
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"Yeah" forKey:@"username"];
    [dict setObject:@"eqe74squbaah9eqvk7bok3rh09" forKey:@"session"];
    [dict setObject:userid forKey:@"user_id"];
    NSMutableArray *arr=[NSArray arrayWithObjects:@"Yeah", @"eqe74squbaah9eqvk7bok3rh09", userid, nil];

    NSString *eventName=@"'Yeah',";
    eventName=[eventName stringByAppendingString:@"'eqe74squbaah9eqvk7bok3rh09',"];
    eventName=[eventName stringByAppendingString:@"'"];
    eventName=[eventName stringByAppendingString:userid];
    eventName=[eventName stringByAppendingString:@"'"];

   // NSLog(@"This is the string to be sent %@",eventName);

    [socketIO sendEvent:@"login" withData:eventName andAcknowledge:cb];
    [socketIO sendEvent:@"subscribe" withData:@"47058" andAcknowledge:cb];
}

这是发送socket.io事件请求的方法。

- (void) sendEvent:(NSString *)eventName withData:(id)data andAcknowledge:(SocketIOCallback)function
{
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:eventName forKey:@"name"];

    // do not require arguments
    if (data != nil) {
        [dict setObject:[NSArray arrayWithObject:data] forKey:@"args"];
    }

    SocketIOPacket *packet = [[SocketIOPacket alloc] initWithType:@"event"];
    packet.data = [SocketIOJSONSerialization JSONStringFromObject:dict error:nil];
    packet.pId = [self addAcknowledge:function];
    if (function) {
        packet.ack = @"data";
    }
    [self send:packet];
}

1 个答案:

答案 0 :(得分:0)

我想到的第一件事就是完全自己制作字符串:

NSString Query = [stringFormatWithString "{\"args\":[{\"username\":\"%@\",     \"id\":\"%@\"}],\"name\":\"%@\"}", usernameVariable,idVariable,nameVariable];