Problem with Obj-C request


#1

The code below seems to be correct, however, I’m receiving an “Authorization Required” message when I NSLog the full response from FlightAware. What am I doing wrong? When I put the resulting URL into a browser, the METAR information is returned properly. A bit new to Obj-C so maybe I’m missing something?



- (void)fetchWX
{
    NSLog(@"fetchWX");
    NSString *requestString = [NSString stringWithFormat:@"http://FA_USERNAME:%@@flightxml.flightaware.com/json/FlightXML2/Metar?airport=%@", FLIGHTAWARE_API_KEY, _airport];
    
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]];
    [req setHTTPMethod:@"GET"];

    NSURLSessionDataTask *dataTask = [self.urlSession dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSArray *wx = [jsonObject objectForKey:@"MetarResult"];

   }];

EDIT: I tried the FlightAware Objective-C example using NSURLConnection, and it worked fine. Would like to use the newer NSURLSession though in my app.


#2

Got an answer to this elsewhere. I’m new to Objective-C/iOS and should have read up more on NSURLSession. The fix is below for those who might be interested. One of the NSURLSession delegate methods is used.



- (void)fetchWX
{
    
    NSLog(@"fetchWX");
    NSString *requestString = [NSString stringWithFormat:@"http://%@:%@@flightxml.flightaware.com/json/FlightXML2/Metar?airport=%@", FLIGHTAWARE_USERNAME, FLIGHTAWARE_API_KEY, _airport];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    config.HTTPAdditionalHeaders = @{ @"Accept":@"application/json"};
    NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    
    NSURL *url = [NSURL URLWithString:requestString];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"jsonObject is %@",jsonObject);
    }];
    
    [dataTask resume];
}


-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
    
    NSString *user = FLIGHTAWARE_USERNAME;
    NSString *password = FLIGHTAWARE_API_KEY;
    
    NSLog(@"didReceiveChallenge");
    
    NSURLCredential *secretHandshake = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistenceForSession];
    
    completionHandler(NSURLSessionAuthChallengeUseCredential,secretHandshake);
}