ioscurlnsurlsessionhttp-deletensurlsessiontask

How to delete an recipe in form of JSON from a server?


I write a code that get recipes in form of JSON from a server and present it into a UItable.

NSURL *url = [NSURL URLWithString:@"http://domain.com/recipes"];
    [config setHTTPAdditionalHeaders:@{@"Authorization":@" Token token=\"3f71235466468b7f7\""}];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:[NSOperationQueue mainQueue]];

    [[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        recipes= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       [self.tableView reloadData];

    }
      ] resume];

This server is written in Ruby. Now I want to write a request to delete a recipe. Here it is the instruction of my server . It said that I should use following curl to delete a recipes:

Delete recipes DELETE: /recipes/:id In Curl it would be something like that:

curl -H 'Authorization: Token token="0b774d575632b"' -X DELETE http://domain.com/recipes/22

Does anybody know how can I implement delete method?


Solution

  • Instead of dataTaskWithURL:, which only allows GET requests, you should use dataTaskWithRequest:.

    Create an NSMutableURLRequest with the appropriate URL, and set its HTTPMethod property to @"DELETE". You can then use that request in your NSURLSession.