最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ios - UIWebView HTTP Basic Auth handling - Stack Overflow

programmeradmin1浏览0评论

I have an app from old Objective-C era which uses UIWebView. It now requires to handle HTTP basic auth. Note: I know WKWebView is a new webview.

Google search finds this as an incomplete sample code. NSURLConnection and Basic HTTP Authentication in iOS

// Setup NSURLConnection
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:30.0];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[connection release];

// NSURLConnection Delegates
- (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");
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    ...
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    ...
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    ...
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    ...
}

I don't understand how to use these delegate functions:

didReceiveResponse()
didReceiveData()
connectionDidFinishLoading()
didFailWithError()

It would be appreciated if there is a small working smpale code, which is helpful to understand how it as all together works. Hours of google searches does not give such a sample. (Maybe because it is obsolete).

Also it would be great if another sample code of "POST" method version is given. Then I can integrate these codes into my app.

发布评论

评论列表(0)

  1. 暂无评论