Objective-C在NSURLAuthenticationChallenge之后等待响应

时间:2014-02-12 16:22:57

标签: objective-c nsurlconnection nsurlcredential

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

Session.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方法等待传递凭据然后等待响应?

1 个答案:

答案 0 :(得分:0)

建议:

  • 如果可能,请转至iOS7。

  • 一旦你这样做,你应该选择闪亮的新NSURLSession,它取代NSURLConnectionThis是一个开始的好地方。

  • 许多人也喜欢AFNetworking