I’m trying to create a new data object using the REST API on iOS, as follows:
NSString *url= @“http://api.backendless.com/v1/data/MyData”;
NSString *dataString= @"{data:“some data”}";
NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@“POST”];
[request setValue:<my-app-id> forHTTPHeaderField:@“application-id”];
[request setValue:<my-secret-key> forHTTPHeaderField:@“secret-key”];
[request setValue:@“REST” forHTTPHeaderField:@“application-type”];
[request setValue:[NSString stringWithFormat:@"%d", [data length]] forHTTPHeaderField:@“Content-Length”];
[request setHTTPBody:data];
NSData *responseData= [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog( @"%@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] );
Here’s the output:
2013-11-06 17:54:59.281 XXXXXX[6982:1403] Entity can’t be empty
Thanks Mark, that worked. I’m now having a problem with the update:
<body>
<h1>Action not found</h1>
<p id="detail">
For request 'POST /v1/data/MyData/<objectID>
</p>
</body>
Hi Russell,
Any chance you could post the code which makes the request?
Regards,
Mark
NSString *url= [NSString stringWithFormat:@“http://api.backendless.com/v1/data/MyData/DCF92457-…”];
NSString *dataString= @"{\"data\":\"some updated data\"}";
NSData *data = [dataString
dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:@"1775476F" forHTTPHeaderField:@"application-id"];
[request setValue:@"937F8ED7" forHTTPHeaderField:@"secret-key"];
[request setValue:@"REST" forHTTPHeaderField:@"application-type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [data length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:data];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *responseData= [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Make sure to use HTTP PUT. I think your code is doing HTTP PUT. So change this:
[request setHTTPMethod:@"POST"];
to this:
[request setHTTPMethod:@"PUT"];
make sure to add the following line of code and it will work:
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
Cheers,
Mark