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

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

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

存在三个问题:
  • 注释掉的行代码没有给出任何错误,但在该行崩溃(调试时)
  • 在[request setValue:authHeader forHTTPHeaderField:@“Authorization”]上;我收到错误消息:“NSURLRequest的无可见接口声明选择器setHTTPHeaderField”
  • 另外,我也收到警告-最后一行中未使用的变量“connection”。我不确定这整个过程如何运作,是否可以通过任何简单的示例或更正获得赞赏。

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

    更新:委托方法
      - (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.");
    
     }
    

    最佳答案

    NSURLRequest更改为NSMutableURLRequest以访问它的setValue:forHTTPHeaderField方法,如果它是共享的Web主机,则还添加一个HOST标头。

    最后,您必须start连接:

    [connection start];
    

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

    10-08 07:49