1

我正在尝试创建一个发送登录信息共享点服务器的登录屏幕,我希望能够成功登录。

有很多我无法使用的旧示例和库。但是花了几个小时后,我发现这个链接是所有问题的关键

http://transoceanic.blogspot.com/2011/10/objective-c-basic-http-authorization.html

我的代码现在看起来像这样:

- (void) startLogin {

NSURL *url = [NSURL URLWithString:@"http://site-url.com"];

NSString *loginString =(NSMutableString*)[NSString stringWithFormat:@"%@:%@",usernameTextField.text,passwordTextField.text];

NSData *encodedLoginData=[loginString dataUsingEncoding:NSASCIIStringEncoding];

NSString *authHeader=[NSString stringWithFormat:@"Basic %@",  [encodedLoginData base64Encoding]];

NSURLRequest *request = [NSURLRequest requestWithURL:url
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:3.0];


//    [request setValue:authHeader forKey:@"Authorization"];

[request setValue:authHeader forHTTPHeaderField:@"Authorization"];
[request setHTTPMethod:@"POST"];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

存在三个问题:

  • 注释掉的行代码没有给出任何错误,但它在该行崩溃(在调试时)

  • on [request setValue:authHeader forHTTPHeaderField:@"Authorization"]; 我收到错误“NSURLRequest 没有可见界面声明选择器 setHTTPHeaderField”

  • 此外,我收到警告 - 最后一行中未使用的变量“连接”。我不确定这整件事是如何运作的,任何简单的例子或更正都值得赞赏。

我还想知道是否还有其他简单的基本身份验证方法。

更新:委托方法

  - (void)connection:(NSURLConnection *)connection
 didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    // Access has failed two times...
if ([challenge previousFailureCount] > 1)
{

       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Authentication Error"
                                                    message:@"Too many unsuccessul login attempts."
                                                   delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

    [alert show];
}
else
{
    // Answer the challenge
    NSURLCredential *cred = [[NSURLCredential alloc] initWithUser:@"admin" password:@"password"
                                                       persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
  }
 }


 - (void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSLog(@"Connection success.");

 }

 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
 {
  NSLog(@"Connection failure.");

 }
4

1 回答 1

2

更改NSURLRequestNSMutableURLRequest访问它的方法,如果它是一个共享的网络主机setValue:forHTTPHeaderField,也添加一个标题。HOST

最后,您必须start连接:

[connection start];

此外,请确保您已经NSURLConnectionDelegate为回调设置了委托方法。

于 2013-08-01T19:29:11.127 回答