user4880042
user4880042

Reputation:

Objective C - HTTP GET Request API

I've been trying to query Tesco's API Service. Although I've managed comfortably on Python with this, I have been having some trouble with making a request using Objective C. Nothing is being logged on the output. Any help would be appreciated. The program code is shown below:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

        NSURL *url = [NSURL URLWithString:@"https://dev.tescolabs.com/product/?gtin=4548736003446"];
        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

        NSString *postParams = @"subscription key=93a6e21eed2e4ca3a858a0f1fc5aaf03";
        NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

        [urlRequest setHTTPMethod:@"GET"];
        [urlRequest setHTTPBody:postData];

        NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSLog(@"Response: %@",response);
            NSLog(@"Data: %@",data);
            NSLog(@"Error: %@",error);
        }];
        [dataTask resume];
    }
    return 0;
}

Upvotes: 1

Views: 4980

Answers (5)

user4880042
user4880042

Reputation:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

        NSURL *url = [NSURL URLWithString:@"https://dev.tescolabs.com/product/? ... "];

        NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithURL: url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSLog(@"Response: %@",response);
            NSLog(@"Data: %@",data);
            NSLog(@"Error: %@",error);
            CFRunLoopStop(CFRunLoopGetCurrent());
            exit(EXIT_SUCCESS);
        }];
        [dataTask resume];
    }

    CFRunLoopRun();
    return 0;
}

Upvotes: 0

vadian
vadian

Reputation: 285039

Basically you need a run loop to perform a background task.

Your request does not work because the body POST data are not considered using a GET request.
All parameters must be passed in the URL.

To implement the run loop just use CFRunLoopRun() and CFRunLoopStop().

Do not use NSRunLoop ... runUntilDate with a while loop

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

        NSURL *url = [NSURL URLWithString:@"https://dev.tescolabs.com/product/? ... "];

        NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithURL: url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSLog(@"Response: %@",response);
            NSLog(@"Data: %@",data);
            NSLog(@"Error: %@",error);
            CFRunLoopStop(CFRunLoopGetCurrent());
            exit(EXIT_SUCCESS);
        }];
        [dataTask resume];
    }

    CFRunLoopRun();
    return 0;
}

Upvotes: 1

Mazyod
Mazyod

Reputation: 22559

I had no choice but to present an answer ... Notice the runloop code:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

        NSURL *url = [NSURL URLWithString:@"https://dev.tescolabs.com/product/?gtin=4548736003446"];
        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

        NSString *postParams = @"subscription key=93a6e21eed2e4ca3a858a0f1fc5aaf03";
        NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

        [urlRequest setHTTPMethod:@"GET"];
        [urlRequest setHTTPBody:postData];

        __block BOOL done = NO;
        NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSLog(@"Response: %@",response);
            NSLog(@"Data: %@",data);
            NSLog(@"Error: %@",error);
            done = YES;
        }];
        [dataTask resume];

        while (!done) {
            NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:0.1];
            [[NSRunLoop currentRunLoop] runUntilDate:date];
        }
    }
    return 0;
}

Upvotes: 1

Ravi Panchal
Ravi Panchal

Reputation: 1355

Try this u need to pass subscription key in header in this request

NSDictionary *headers = @{ @"ocp-apim-subscription-key": @"YourKey"};

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"YourURL"]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
[request setHTTPMethod:@"GET"];
[request setAllHTTPHeaderFields:headers];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error) {
                                                    NSLog(@"%@", error);
                                                } else {
                                                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                    NSLog(@"%@", httpResponse);
                                                }
                                            }];
[dataTask resume];

Upvotes: 0

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

-dataTaskWithRequest:completionHandler: is asynchronous. You are queuing up an action which would be completed later then exiting the program before it completes.

You need a mechanism to wait for the data task to complete before exiting the program.

See: https://stackoverflow.com/a/34200617/1298400 for an example waiting mechanism.

Upvotes: 0

Related Questions