Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP PUT method with NSURLSession

I'm struggling with NSURLSession class introduced in iOS 7 SDK and I'm stuck at a point, where I need to call my REST API with PUT method.

I've already implemented GET and POST methods, which are working fine using this:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:httpMethod]; // GET/POST works, PUT does not
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error){
            // do something here
            ( ... )
        } else {
            // process error
            ( ... )
        }
    }];
    [postDataTask resume];

Unfortunately, setting httpMethod to PUT doesn't seem to work (it behaves as GET). Calling contents of *url from cURL console works fine - so the path to API is OK.

How can I create valid PUT request to my API using NSURLSession?

like image 358
Sebastian Łuczak Avatar asked Nov 08 '13 13:11

Sebastian Łuczak


1 Answers

You need to set the data with NSMutableURLRequest setHTTPBody method, the same as with POST.

- (void)setHTTPBody:(NSData *)data
like image 166
zaph Avatar answered Oct 06 '22 23:10

zaph