I know that there are similar questions posted as I have read though most all of them and still am having problems. I am trying to send JSON data to my server, but I do not think the JSON data is being received. I'm just not sure what I am missing. Below is my code...
Method to send data to server.
- (void)saveTrackToCloud
{
NSData *jsonData = [self.track jsonTrackDataForUploadingToCloud]; // Method shown below.
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString); // To verify the jsonString.
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:http://www.myDomain.com/myscript.php] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[postRequest setHTTPMethod:@"POST"];
[postRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[postRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[postRequest setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[postRequest setHTTPBody:jsonData];
NSURLResponse *response = nil;
NSError *requestError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&requestError];
if (requestError == nil) {
NSString *returnString = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
NSLog(@"returnString: %@", returnString);
} else {
NSLog(@"NSURLConnection sendSynchronousRequest error: %@", requestError);
}
}
Method jsonTrackDataForUploadingToCloud
-(NSData *)jsonTrackDataForUploadingToCloud
{
// NSDictionary for testing.
NSDictionary *trackDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"firstValue", @"firstKey", @"secondValue", @"secondKey", @"thirdValue", @"thirdKey", nil];
if ([NSJSONSerialization isValidJSONObject:trackDictionary]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:trackDictionary options:NSJSONWritingPrettyPrinted error:&error];
if (error == nil && jsonData != nil) {
return jsonData;
} else {
NSLog(@"Error creating JSON data: %@", error);
return nil;
}
} else {
NSLog(@"trackDictionary is not a valid JSON object.");
return nil;
}
}
And here is my php.
<?php
var_dump($_POST);
exit;
?>
The output that I receive from NSLog(@"returnString: %@", returnString); is...
returnString: array(0) {
}