带有身份验证的NSURLSession的简单示例

时间:2013-12-20 20:56:40

标签: nsurlsession

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

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

我最初使用以下方式进行了身份验证:

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

这工作正常,但我认为我不能添加身份验证。如果可以,我会用它。

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

2 个答案:

答案 0 :(得分:7)

我认为你的问题含糊不清,而且不够明确。也就是说,这是一个解决方案,来自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++;
}

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

答案 1 :(得分: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"];

问候