Simple example of NSURLSession with authentication

偶尔善良 提交于 2019-12-01 12:16:15

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!