**我是 iOS 开发的新手。我正在开发一个小型应用程序,它可以打开指定的 SharePoint 网站 URL,而无需手动传递需要凭据。我尝试打开的 URL 需要凭据,但我想将这些凭据嵌入到我将在 UIWebView 控件中打开 URL 的请求中。我不想在 Safari 中打开 URL。
您能帮我找到解决方案吗?**
**我是 iOS 开发的新手。我正在开发一个小型应用程序,它可以打开指定的 SharePoint 网站 URL,而无需手动传递需要凭据。我尝试打开的 URL 需要凭据,但我想将这些凭据嵌入到我将在 UIWebView 控件中打开 URL 的请求中。我不想在 Safari 中打开 URL。
您能帮我找到解决方案吗?**
您可以使用-connection:didReceiveAuthenticationChallenge:
委托来解决您的问题。首先做一个正常NSURLConnection
如下,
- (void) someMethod
{
NSURLRequest* request = [[NSURLRequest alloc]
initWithURL:[NSURL urlWithString:@"Your sharepoint web url"]
NSURLConnection* connection = [[NSURLConnection alloc]
initWithRequest:request delegate:self];
[connection release];
[request release];
}
之后您会收到回电。在这里,您应该处理凭据的挑战。
- (void) connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
// Make sure to use the appropriate authentication method for the server to
// which you are connecting.
if ([[challenge protectionSpace] authenticationMethod] ==
NSURLAuthenticationMethodBasicAuth)
{
// This is very, very important to check. Depending on how your
// security policies are setup, you could lock your user out of his
// or her account by trying to use the wrong credentials too many
// times in a row.
if ([challenge previousFailureCount] > 0)
{
[[challenge sender] cancelAuthenticationChallenge:challenge];
UIAlertView* alert = [[UIAlertView alloc]
initWithTitle:@"Invalid Credentials"
message:@"The credentials are invalid."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
[challenge useCredential:[NSURLCredential
credentialWithUser:@"someUser"
password:@"somePassword"
persistence:NSURLCredentialPersistenceForSession
forAuthenticationChallenge:challenge]];
}
}
else
{
// Do whatever you want here, for educational purposes,
// I'm just going to cancel the challenge
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
更新 将此代码用于此链接。
-(void)viewDidLoad{
NSString *strWebsiteUlr = [NSString stringWithFormat:@"http://www.roseindia.net"];
NSURL *url = [NSURL URLWithString:strWebsiteUlr];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[webview setDelegate:self]
}
在头文件中
@interface yourViewController : UIViewController<UIWebViewDelegate>{
Bool _authed;
}
@property(强,非原子)IBOutlet UIWebView *webView;