How to implement a REST API HTTP PUT method to update a record in MongoDB with AFNetworking?

884 Views Asked by At

I created a full RESTful API using node.js and mongoDB. Using AFNetworking, I could easily implement GET to retrieve a list of products via the API but I'm having trouble doing a PUT method to update a record. The idea is check if there is a record for this UUIDString, if there is update the record.

If I run a cURL command in terminal. This will work:

Modify with _id value of 6FDCBF3D:

curl -i -X PUT -H 'Content-Type: application/json' -d '{"name": "someName", "someValue": "15"}' http://localhost:3000/iaps/6FDCBF3D/

Objective-c Code:

NSURL *baseURL = [[NSURL alloc] initWithString:@"http://localhost:3000/iaps/"];
           // NSString *uuid = [UIDevice currentDevice].identifierForVendor.UUIDString;
            AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
            [client getPath:@"6FDCBF3D" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSError *jsonError = nil;
                NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:NSJSONReadingMutableContainers error:&jsonError];
//                NSLog(@"Return object: %@", json);
                if (json) {
                    NSString *purchasedPkg = [productIdentifier pathExtension];
                    if ([purchasedPkg isEqualToString:@"productA"]) {
                        NSString *oldPkg = [json objectForKey:@"somevalue"];
                        int newPkgVal = oldPkg.intValue + 1;
                        NSString *newPkg = [NSString stringWithFormat:@"%d",newPkgVal];
                        [json setValue:newPkg forKey:@"somevalue"];
                    }

                    NSMutableURLRequest *request = [client requestWithMethod:@"PUT" path:@"6FDCBF3D" parameters:nil];
                    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:&jsonError];
                    AFHTTPRequestOperation *op = [client HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
                        NSLog(@"put success");
                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        NSLog(@"put failed");
                    }];
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"%@", error);
            }];
1

There are 1 best solutions below

0
On

AFNetworking provides put method as follows:

- (void)putPath:(NSString *)path 
     parameters:(NSDictionary *)parameters 
        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure