Reputation: 3115
This issue is pretty simple, I'm just having trouble figuring out how to handle it.
I read data with:
[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;
}
Now, just as expected, my delegate method gets called and properly reads the JSON data:
-(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"]);
}
The problem is, since GCDAsyncSocket is Asynchronous, this block of code
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;
}
after
[asyncSocket readDataWithTimeout:-1 tag:2];
Is called before the data has a chance to be read in. How would I go about ensuring that the data is read, and then analyze it.
Upvotes: 0
Views: 1647
Reputation: 14834
That block of code needed to be in the didReadData callback method, like so:
-(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;
}
}
Upvotes: 1