按时读取GCDAsyncSocket的响应(iOS)

时间:2012-08-19 00:38:26

标签: ios sockets cocoaasyncsocket gcdasyncsocket

这个问题非常简单,我只是在弄清楚如何处理它。

我用以下内容阅读数据:

[asyncSocket readDataWithTimeout:-1 tag:2];

NSString *failure = [serverJSONResponseParsed objectForKey:@"failure"];
NSLog(@"Contents of string failure: %@", failure);

if ([failure isEqualToString:@"none"]) {
    NSLog(@"Success Sending String");
    return TRUE;
}
else {
    NSLog(@"Failure: %@",failure);
    return FALSE;
}

现在,正如预期的那样,我的委托方法被调用并正确读取JSON数据:

-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    NSError *error;
    NSLog(@"didReadData: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    serverJSONResponseParsed = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    NSLog(@"didReadData test after dict: %@", [serverJSONResponseParsed objectForKey:@"failure"]);
}

问题是,因为GCDAsyncSocket是异步的, 这段代码

NSString *failure = [serverJSONResponseParsed objectForKey:@"failure"];
NSLog(@"Contents of string failure: %@", failure);

if ([failure isEqualToString:@"none"]) {
    NSLog(@"Success Sending String");
    return TRUE;
}
else {
    NSLog(@"Failure: %@",failure);
    return FALSE;
}

[asyncSocket readDataWithTimeout:-1 tag:2];

在数据有机会被读入之前被调用。我将如何确保读取数据,然后进行分析。

1 个答案:

答案 0 :(得分:1)

这段代码需要在didReadData回调方法中,如下所示:

    -(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
        NSError *error;
        NSLog(@"didReadData: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        serverJSONResponseParsed = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        NSLog(@"didReadData test after dict: %@", [serverJSONResponseParsed objectForKey:@"failure"]);

    NSString *failure = [serverJSONResponseParsed objectForKey:@"failure"];
    NSLog(@"Contents of string failure: %@", failure);

    if ([failure isEqualToString:@"none"]) {
        NSLog(@"Success Sending String");
        return TRUE;
    }
    else {
        NSLog(@"Failure: %@",failure);
        return FALSE;
    }
}