Вопрос

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?

Это было полезно?

Решение

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

- (void)setHTTPBody:(NSData *)data
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top