【问题标题】:Reading response from GCDAsyncSocket on time (iOS)按时从 GCDAsyncSocket 读取响应(iOS)
【发布时间】:2012-08-19 00:38:25
【问题描述】:

这个问题很简单,就是不知道怎么处理。

我通过以下方式读取数据:

[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];

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

【问题讨论】:

    标签: ios sockets cocoaasyncsocket gcdasyncsocket


    【解决方案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;
        }
    }
    

    【讨论】:

    • 谢谢。感谢您回答了我几乎所有的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多