在过去的几个小时里,我一直在用头撞墙,在任何地方都找不到一丝解决方案。我正在开发一个应用程序来学习如何使用 JSON,所以我只是在构建一个简单的应用程序,起初它只是返回我在 GitHub 上的所有存储库的列表。我能够毫无问题地从 NSURLConnection 返回的数据中提取 JSON 响应,不幸的是,当我尝试访问需要身份验证的任何内容时,响应总是{
message = "Not Found";
}
如果我发送请求以获取有关我的用户名的公共信息,我会得到正确的回复所有正确的信息,所以我知道我正在与 api.github.com 成功沟通。首先开始我使用的请求:
-(IBAction)retriveRepos:(id)sender
{
responseData = [[NSMutableData data] retain];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://api.github.com/user/repos"]];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
当- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
被调用时,身份验证方法会返回NSURLAuthenticationMethodServerTrust
(我觉得很奇怪,因为我觉得我应该提供用户名和密码才能登录)。根据 Apple 的文档,我需要NSURLCredential
使用initWithTrust:
. 我在谷歌上搜索了答案,最后找到了一些地方,说只是serverTrust
从传入protectionSpace
的NSURLAuthenticationChallenge
那个中获取。这样做根本没有任何影响的迹象,实际上看起来我NSURLCredential
的几乎什么都没有。
if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodServerTrust) {
NSLog(@"challenge.protectionSpace.serverTrust: %@", challenge.protectionSpace.serverTrust); // This logs "challenge.protectionSpace.serverTrust: <SecTrust 0x10340b2e0 [0x7fff7cc12ea0]>"
NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
NSLog(@"credential: %@", credential); // Always logs something like "credential: <NSURLCredential: 0x1002d2f20>: (null)"
NSURLCredential *otherCredential = [[NSURLCredential alloc] initWithUser:@"user" password:@"password" persistence:NSURLCredentialPersistencePermanent];
NSLog(@"otherCredential: %@", otherCredential); // This logs otherCredential: <NSURLCredential: 0x1018d0840>: user"
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
我还使用了更广泛的日志记录,表明它credential
确实存在(起初我认为它根本没有被创建)但是它没有任何属性 set certificates: (null)
hasPassword: 0
identity: (null)
password: (null)
。我只能假设问题出在我的身份验证中,但我完全按照我找到的示例进行操作。我正在使用 Lion 的 GM 预览版,所以我想我可能发现了一个错误,或者 GitHub API 中存在一些错误,但考虑到我的技能水平,我发现我更有可能是一个正在寻找的白痴坐在我面前的答案。如果有人知道一个很好的指南,它实际上会引导您完成身份验证的所有步骤(最好是所有样式),而不是严重缺乏 Apple URL 加载指南,它只是说使用一种方法但没有说明在哪里SecTrustRef
来自它将不胜感激。