我正在尝试创建一个登录屏幕,发送登录信息sharepoint服务器,我希望能够成功登录。
我无法使用大量旧的示例和库。但花了几个小时后,我发现这个链接有所有
的关键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];
有三个问题:
注释掉的行代码不会出现任何错误,但会在该行崩溃(调试时)
on [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.");
}
答案 0 :(得分:2)
将NSURLRequest
更改为NSMutableURLRequest
以访问其setValue:forHTTPHeaderField
方法,并添加HOST
标头,如果它是共享网络主机。
最后,您必须start
连接:
[connection start];
另外,请确保为回拨设置NSURLConnectionDelegate
委托方法。