2014-02-12 58 views
0

我是新来的目标C。我正在创建一个需要登录的网站的移动版本。我想弄清楚如何让用户名和密码成为收到NSURLAuthenticationChallenge后传入。这里是我的代码:Objective-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方法等待传入凭据,然后等待响应(如果凭据有效)?

回答

0

建议:

  • 如果可能的话,请iOS7只。

  • 一旦你这样做,你应该更喜欢有光泽的,新的NSURLSession,它取代NSURLConnectionThis是上手的好地方。

  • 许多人也喜欢AFNetworking