2014-10-04 71 views
0

我是新来的Objective-C,并努力让下面的代码正常工作。注销dataString告诉我API正在返回“Authentication Required”消息。但是,当我将结果URL放入浏览器时,我想要的信息会正确返回。我错过了什么? NSURLSession是否在做一些改变请求?使用NSURLSession进行“需要身份验证”。用户/密钥正确

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

    NSURLSessionDataTask *dataTask = [self.urlSession dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 

    NSLog(@"%@", dataString); 
}]; 

[dataTask resume]; 
} 

有一个在我与的正常工作相似的结构的应用程序的另一种方法,并使用NSURLConnection的FlightAware的同步例子也能正常工作。只是似乎无法使用NSURLSession。

回答

1
NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration]; 
config.HTTPAdditionalHeaders = @{ @"Accept":@"application/json"}; 
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; 

NSURL *url = [NSURL URLWithString:path]; 
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); 
}]; 

并添加此代理方法,该代理方法将被调用一次以解决身份验证问题。

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler { 

    NSString *user = @"YourUserName"; 
    NSString *password = @"YourKey"; 

    NSLog(@"didReceiveChallenge"); 

    // should prompt for a password in a real app but we will hard code this baby 
    NSURLCredential *secretHandshake = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistenceForSession]; 

    // use block 
    completionHandler(NSURLSessionAuthChallengeUseCredential,secretHandshake); 
} 

我测试了它,它工作。

+0

工作。猜猜我需要仔细阅读文档。谢谢 – Ja5onHoffman 2014-10-04 14:52:49

相关问题