Search code examples
iosobjective-cios9nsurlsession

Make http DELETE request with NSURLSession


I'm trying to make an http DELETE request using NSURLSession, but it's not completely working. The server deletes the resource, but the NSURLSession method dataTaskWithRequest: completionHandler: returns a time out error after waiting for the specified timeout.

I am not using NSURLConnection because it is deprecated.

Of the NSURLSession methods to use, I chose dataTaskWithRequest because it is most similar to the method I use for http GET: dataTaskWithUrl: completionHandler. The methods beginning with "uploadTask" and "downloadTask" don't seem appropriate for a DELETE, but downloadTaskWithRequest: completionHandler: 'worked' in the same way as the dataTask method above. The server deleted the resource, but the method returned a time out error.

Here is the code:

+(void)httpDelete: (NSString*)url completionHandler: (void(^)(id, NSError*))complete 
{
    NSURLSessionConfiguration *urlSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSMutableDictionary* dictionaryAdditionalHeaders = [[NSMutableDictionary alloc] init];

    NSString* stringBearerToken = @"...";
    NSString* stringApiKey = @"...";

    [dictionaryAdditionalHeaders setObject:stringBearerToken forKey:@"Authorization"];
    [dictionaryAdditionalHeaders setObject:stringApiKey forKey:@"x-api-key"];
    [dictionaryAdditionalHeaders setObject:@"application/json" forKey:@"Content-Type"];
    [dictionaryAdditionalHeaders setObject:@0 forKey:@"Content-Length"];

    [urlSessionConfiguration setHTTPAdditionalHeaders: dictionaryAdditionalHeaders];

    NSURLSession *urlSession = [NSURLSession sessionWithConfiguration: urlSessionConfiguration delegate:nil delegateQueue:[NSOperationQueue mainQueue]];

    NSMutableURLRequest* mutableUrlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5];
    [mutableUrlRequest setHTTPMethod: @"DELETE"];

    [[urlSession dataTaskWithRequest:mutableUrlRequest completionHandler: ^(NSData *data, NSURLResponse* response, NSError* error)
    {
        if(error != nil)
        {
            complete(response, error);
        }
        else
        {
            complete(response, nil);
        }
   }] resume];
}

Using Postman, the DELETE call returns with a 204 immediately.

Am I using NSURLSession correctly for a delete request?


Solution

  • It turns out the Amazon API Gateway incorrectly sends a Content-Length header with a 204 response. They added the issue to their backlog March 21, 2016 according to this AWS forum. When I increased the timeout interval of the NSMutableURLRequest to a ridiculous 300 seconds, the dataTaskWithRequest method returns with a real response instead of timing out.