gpt4 book ai didi

ios - "Authentication Required"与 NSURLSession。用户/ key 正确

转载 作者:行者123 更新时间:2023-11-29 02:37:24 25 4
gpt4 key购买 nike

我是 Objective-C 的新手,正在努力让以下代码正常工作。注销 dataString 告诉我 API 正在返回“需要身份验证”消息。然而,当我将生成的 URL 放入浏览器时,我想要的信息被正确返回。我错过了什么? 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];
}

在我的应用程序中有另一种方法具有类似的结构,可以正常工作,FlightAware 的使用 NSURLConnection 的同步示例也可以正常工作。似乎无法使用 NSURLSession。

最佳答案

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);
}];

并添加此委托(delegate)方法,该方法将被调用一次以解决身份验证问题。

-(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);
}

我已经测试过它并且有效。

关于ios - "Authentication Required"与 NSURLSession。用户/ key 正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26193241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com