I don’t know anything about JSON, and I need to send a request to the server and read the data coming from it using only the iPhone.
I tried using the jason-framework
for this, but after reading the documents, I was not able to figure out how to build the object and send it on request. So I decided to adapt another code that I saw here on SO.
The object I need is:
{"code": xxx}
I have a problem here. This xxx is NSData, so I suspect that I need to convert this data to a string, and then use this string to create an object and send it on request.
server response is also a JSON object in the form
{"answer": "yyy"} where yyy is a number between 10,000 and 99999
this is the code that i still have.
- (NSString *)checkData:(NSData) theData {
NSString *jsonObjectString = [self encode:(uint8_t *)theData length:theData.length];
NSString *completeString = [NSString stringWithFormat:@"http://www.server.com/check?myData=%@", jsonObjectString];
NSURL *urlForValidation = [NSURL URLWithString:completeString];
NSMutableURLRequest *validationRequest = [[NSMutableURLRequest alloc] initWithURL:urlForValidation];
[validationRequest setHTTPMethod:@"POST"];
NSData *responseData = [NSURLConnection sendSynchronousRequest:validationRequest returningResponse:nil error:nil];
[validationRequest release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding];
NSInteger response = [responseString integerValue];
NSLog(@"%@", responseString);
[responseString release];
return responseString;
}
- (NSString *)encode:(const uint8_t *)input length:(NSInteger)length {
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData *data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t *output = (uint8_t *)data.mutableBytes;
for (NSInteger i = 0; i < length; i += 3) {
NSInteger value = 0;
for (NSInteger j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger index = (i / 3) * 4;
output[index + 0] = table[(value >> 18) & 0x3F];
output[index + 1] = table[(value >> 12) & 0x3F];
output[index + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[index + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
ret
urn [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
}
all this code gives me errors. Either a BAD URL or java exception.
What is wrong with this code?
If you guys want to give another solution using json-framework, tell me how to encode an object using this pair ("code", "my NSData are converted to a string here") ...
Thanks for any help.
source
share