How can I pass credentials when using NSURLSession

I am trying to login to my computer using utorrent webui.

I am currently using the following code:

- (void)login
{
NSURL *feedsURL = [NSURL URLWithString:@"http://localhost:12345/"];

NSString *user = @"username";
NSString *password = @"password";
NSURLCredential *defaultCredential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistencePermanent];

NSString *host = [feedsURL host];
NSInteger port = [[feedsURL port] integerValue];
NSString *protocol = [feedsURL scheme];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic];

NSURLCredentialStorage *credentials = [NSURLCredentialStorage sharedCredentialStorage];
[credentials setDefaultCredential:defaultCredential forProtectionSpace:protectionSpace];

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config setURLCredentialStorage:credentials];

NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil];
[[session dataTaskWithURL:feedsURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (!error) {
        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
        if (httpResp.statusCode == 200) {
            NSLog(@"Woo! everything is working");
        } else {
            NSLog(@"Hrmmm... error %@ occured", error);
        }
    } else {
        NSLog(@"Hrmmm... error %@ occured", error);
    }

}] resume];

I can see that the page is just fine when using a web browser on the desktop, however in my application it always returns error 401 (not authorized).

I think this is because credentials are not used? If so, what is the correct way to use it? Also, NSURLSessionDelegate methods are not called. Is there anything else I should do?

+4
source share
2 answers

HTTP Basic, , ; , , , . , curl -v, , .

, , , : - , . .

+1

localhost IP-

0

All Articles