Simple example of NSURLSession with authentication

后端 未结 2 1143
眼角桃花
眼角桃花 2021-01-15 08:31

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 int

相关标签:
2条回答
  • 2021-01-15 08:51

    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

    0 讨论(0)
  • 2021-01-15 09:02

    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.

    0 讨论(0)
提交回复
热议问题