I was wondering on how do I handle the following parameter PUT
request? How do I store the parameter (assuming using NSDictionary
) so I can send it to the server running php. Any tips or suggestions is appreciated.
curl -X PUT -d {"questions":[{"type":"control_head" }]}
p.s. the above is what the API document given me. {"questions":[{"type":"control_head" }]}
is the parameter I need to use just in case you didn't get that that.
If doing it yourself, you'd instantiate a NSMutableURLRequest
object, modify it as suggested by your curl
(e.g. PUT
request, JSON body, etc.), and then initiate the request via NSURLConnection
or NSURLSession
.
That yields something like:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"PUT";
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSDictionary *parameters = @{@"questions":@[@{@"type": @"control_head"}]};
NSError *error;
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!data) {
NSLog(@"sendAsynchronousRequest error: %@", connectionError);
return;
}
// parse the response here; given that the request was JSON, I assume the response is, too:
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (!responseObject) {
NSLog(@"parsing response failed: %@", parseError);
NSLog(@"body of response was: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
return;
}
// now you can look at `responseObject`
}];
You can simplify this further by using a library like AFNetworking:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = @{@"questions":@[@{@"type": @"control_head"}]};
[manager PUT:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
(I haven't checked the syntax of the AFNetworking request, but it's something along those lines.)