在带有身份验证的webview中加载URL无效

时间:2014-05-20 10:30:54

标签: ios authentication webview

我正在尝试将一个image加载到web view但它正在加载一些黑条。如果我在浏览器中加载了用户名和密码的网址,则显示图像。但我无法参见项目web view。请帮助我。

NSString *postString = [NSString stringWithFormat:@"username=%@&password=%@",username, password];
NSLog(@"%@", postString);
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:self.address]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
self.webview.delegate = self;
[self.webview loadRequest:request];

1 个答案:

答案 0 :(得分:0)

    NSError *error = nil;

        NSString *username = @"";
        NSString *password =@"";
        // Add Domain to the User name
       username= @"abc";
       password= @"xyz";

        NSString *postString = [[NSString stringWithFormat:@"%@:%@",username, password] base64EncodedString];
        NSString *authString = [NSString stringWithFormat: @"Basic %@", postString];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.address] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
        [request setValue:authString forHTTPHeaderField:@"Authorization"];
        self.imagedata = [[NSMutableData alloc] init];
        NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        [urlConnection start];


// NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge previousFailureCount] == 0) {
        NSLog(@"received authentication challenge");


        NSString *username = @"abc";
        NSString *password =@"xyz";


        NSURLCredential *newCredential = [NSURLCredential credentialWithUser:username
                                                                    password:password
                                                                 persistence:NSURLCredentialPersistenceForSession];
        NSLog(@"credential created");
        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
        NSLog(@"responded to authentication challenge");
    }
    else {
        NSLog(@"previous authentication failure");
    }
}