Simple example of NSURLSession with authentication

2019-02-19 19:20发布

问题:

I have written a REST service that serves up some data. It is passcode protected.

I am trying to write a background process that will grab the data and stuff it into a sqlLite db I have in the app.

I did this initially without authentication using :

- (void) callWebService {
    dispatch_sync(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL:
                        scoularDirectoryURL];
        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
    });
}

This worked fine but I don't think I can add authentication to that. If I can I would just use that.

What I am looking for is a nice, simple explanation of NSURLSession using user/password authentication.

回答1:

I think your question is vague and underspecified. That said, here's one solution, from here:

-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(    NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
    if (_sessionFailureCount == 0) {
        NSURLCredential *cred = [NSURLCredential credentialWithUser:self.userName password:self.password persistence:NSURLCredentialPersistenceNone];        
    completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
    } else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
    _sessionFailureCount++;
}

I strongly recommend that you read and re-read the Apple docs on this.



回答2:

For me the following code works:

NSString *userName=@"user:";
NSString *userPassword=@"password";
NSString *authStr= [userName stringByAppendingString:userPassword];
NSString *url=@"http://000.00.0.0:0000/service.json";

NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];

[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]

                       completionHandler:^(NSURLResponse *response,
                                           NSData *data, NSError *connectionError)

NSDictionary *theDictionary = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:0
                                                                    error:NULL];

 NSDictionary *host = [theDictionary objectForKey : @"host"];
         // json nested
            self.label.text = [host objectForKey:@"key1"];
            self.label.text = [host objectForKey:@"key2"];

regards