0

我是目标 C 的新手。我正在创建一个需要登录的网站的移动版本。我试图弄清楚在收到 NSURLAuthenticationChallenge 后如何允许传入用户名和密码。这是我的代码:

会话.m

// log in
-(BOOL)logIn
{
    if (([Password class] == [NSNull class]) || ([Password length] == 0))
        return NO;

    if (([Username class] == [NSNull class]) || ([Username length] == 0))
        return NO;

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL_CONSTANT]
                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:10.0];

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

    if (!connection)
    {
        return NO;
    }
    return Connected;
}

// handle authentiaction challenge
-(void)connection:(NSURLConnection*)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSLog(@"received auth challenge");
    if ([challenge previousFailureCount] == 0)
    {
        NSLog(@"received auth challenge");
        NSURLCredential *credentials = [NSURLCredential credentialWithUser:Username
                                                                 password:Password
                                                              persistence:NSURLCredentialPersistenceForSession];

        NSLog(@"credential created");
        [[challenge sender] useCredential:credentials forAuthenticationChallenge:challenge];
        NSLog(@"responded to auth challenge");
    }
    else
    {
        Connected = NO;
        NSLog(@"previous auth failure");
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"Data received");
    Connected = YES;
}

用户名和密码都从 UITextField 传递到 Session 对象。这里的问题是在连接获取数据之前返回 NO。我如何告诉 logIn 方法等待凭据被传入,然后在凭据有效时等待响应?

4

1 回答 1

0

建议:

  • 如果可能,请仅使用 iOS7。

  • 一旦你这样做了,你应该更喜欢闪亮的、新NSURLSession的,它取代了NSURLConnection是一个开始的好地方。

  • 许多人还喜欢AFNetworking

于 2014-02-12T17:55:08.363 回答