2014-10-04 74 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

相關問題