AFNetworking 2 authentication with AFHTTPRequestOperation

后端 未结 1 1774
無奈伤痛
無奈伤痛 2021-02-06 03:57

I want to use AFNetworking with a batch operation. I want to download 3 json files.

How to add basic authentication with AFHTTPRequestOperation ?

NSMutab         


        
相关标签:
1条回答
  • 2021-02-06 04:23

    Use AuthenticationChallengeBlock to handle basic authentication challenge.

    [operation setAuthenticationChallengeBlock:
            ^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
       NSURLCredential *cred = [NSURLCredential 
        credentialWithUser:@"username" 
        password:@"password" 
        persistence:NSURLCredentialPersistenceForSession];
    
       [[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
    }];
    

    Edit:

    Another option is to pass authentications in request header.

    NSURLMutableRequest *request = [NSURLMutableRequest
                                    requestWithURL:[NSURL URLWithString:fileURL]];
    NSData* authData = [[[NSString 
        stringWithFormat:@"username:password"] 
            stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] 
                dataUsingEncoding: NSASCIIStringEncoding];
    NSString *finalAuth = [authData base64EncodedString];
    finalAuth = [NSString stringWithFormat:@"Basic %@",finalAuth];
    [request setValue:finalAuth forHTTPHeaderField:@"Authorization"];
    

    Yet another solution :

    NSURLCredential *credential = [NSURLCredential 
        credentialWithUser:@"login" 
        password:@"password" 
        persistence:NSURLCredentialPersistenceForSession];
    
    [operation setCredential:credential];
    
    0 讨论(0)
提交回复
热议问题