2

我编写了一个提供一些数据的 REST 服务。它受密码保护。

我正在尝试编写一个后台进程来获取数据并将其填充到我在应用程序中拥有的 sqlLite db 中。

我最初没有使用身份验证就这样做了:

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

这很好用,但我认为我不能为此添加身份验证。如果可以的话,我会使用它。

我正在寻找的是使用用户/密码身份验证对 NSURLSession 的一个很好、简单的解释。

4

2 回答 2

7

我认为您的问题含糊不清且未详细说明。也就是说,这是一个解决方案,从这里开始

-(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++;
}

我强烈建议您阅读并重新阅读Apple 文档

于 2014-01-20T20:01:30.657 回答
0

对我来说,以下代码有效:

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"];

问候

于 2016-04-21T20:28:31.220 回答