我正在尝试创建一个登录屏幕,该屏幕发送登录信息共享点服务器,我希望能够成功登录。
有很多旧的示例和库我无法使用。但是花了几个小时后,我发现此链接具有所有问题的症结
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];
存在三个问题:
我也想知道是否有其他简单的基本身份验证方法。
更新:委托方法
- (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
委托方法。