iOS:如何为我的NSURL添加凭据



我正在尝试访问我要解析的XML的页面。我正在使用以下代码,只要我不需要凭据即可。如何在此代码中添加凭据?

NSURL *url = [[NSURL alloc] initWithString:URLPath];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[xmlParser setDelegate: self];
success = [xmlParser parse];

我的" urlpath"上方是我的URL字符串。我尝试使用以下URL路径格式,但对我不起作用。http://username:password@mypage.com/path/to/file.aspx?Function=Update

谢谢!

使用NSURLConnectionDelegates

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge previousFailureCount] == 0) {
        NSLog(@"received authentication challenge");
        NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"USER"
                                                                    password:@"PASSWORD"
                                                                 persistence:NSURLCredentialPersistenceForSession];
        NSLog(@"credential created");
        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
        NSLog(@"responded to authentication challenge");    
    }
    else {
        NSLog(@"previous authentication failure");
    }
}

有关更多信息,请参见iOS中的Nsurlconnection和基本HTTP身份验证

最新更新