I am having a problem with my iPhone application that I am building. The app sends a JSON request to a python server and then reads the JSON response from the server. I have the following function that sends data to the server and gets the response and puts it into NSData. (I took out the server address for the post)
+(NSData *)accessServer:(NSMutableDictionary *) dic needResponse:(BOOL) response
{
// Conect to the server
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStringRef remoteHost = CFSTR("");
CFStreamCreatePairWithSocketToHost(NULL, remoteHost, 5687, &readStream, &writeStream);
CFWriteStreamOpen(writeStream);
CFReadStreamOpen(readStream);
// send data
NSData *json = [NSJSONSerialization dataWithJSONObject:dic options:0 error:nil];
NSString *jsonString = [[NSString alloc]initWithData:json encoding:NSUTF8StringEncoding];
jsonString = [NSString stringWithFormat:@"%@%@", jsonString, @"\r\n\r\n"];
UInt8 *writeBuf = (UInt8 *)[jsonString UTF8String];
int writtenBytes = 0;
int bytesToSend = (int)[jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
while(writtenBytes < bytesToSend)
{
writtenBytes += CFWriteStreamWrite(writeStream, writeBuf, bytesToSend-writtenBytes);
}
NSLog(@"Done sending, Sent :%d Total: %d",writtenBytes,bytesToSend);
CFWriteStreamClose(writeStream);
if(response)
{
// get the return data
uint8_t readData[10000];
int readBytes = 1;
int totalRead = 0;
while(readBytes > 0)
{
readBytes = (int)CFReadStreamRead(readStream, readData, 10000);
totalRead += readBytes;
}
CFReadStreamClose(readStream);
return [[NSData alloc]initWithBytes:readData length:totalRead];
}
else
{
CFReadStreamClose(readStream);
return nil;
}
}
The problem is that when I attempted to take the NSData and convert it into a NSString it has a length of 0 and the NSData has a length > 0. The following code is how I take the NSData and convert it to NSString.
NSData *t = [Globals accessServer:getLocationData needResponse:TRUE];
NSString *tempString = [[NSString alloc]initWithData:t encoding:NSUTF8StringEncoding];
This problem seems to happen about 10% of the time. Sometimes it won't happen for an hour and sometimes it happens like 10 times in a row. Any help is appreciated and please let me know if you need any more information that I may have forgotten to put in this.