Basic HTTP Authentication on iPhone

后端 未结 2 528
失恋的感觉
失恋的感觉 2020-12-02 07:50

I\'m trying to get a small twitter client running and I ran into a problem when testing API calls that require authentication.

My password has special characters in

相关标签:
2条回答
  • 2020-12-02 08:35

    You can directly aslo write download the username & password in main URL i.e https://username:password@yoururl.com/

    First of all you need to call NSURLConnection Delegate file:-

    • (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace

      {

      return YES; }

    and then call - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

    {
    if ([challenge previousFailureCount] == 0)
            {
                NSURLCredential *newCredential;
    
                newCredential = [NSURLCredential credentialWithUser:@"username"
                                                           password:@"password"
                                                        persistence:NSURLCredentialPersistenceForSession];
                NSLog(@"NEwCred:- %@ %@", newCredential, newCredential);
                [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
            }
            else
            {
                [[challenge sender] cancelAuthenticationChallenge:challenge];
                NSLog (@"failed authentication");
            }
    }
    
    0 讨论(0)
  • 2020-12-02 08:46

    Two things. Firstly you have to use the async methods rather than the synchronous/class method.

    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:req]
                                                                   cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                               timeoutInterval:30.0];
    
    // create the connection with the request
    // and start loading the data
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    

    The authentication is managed by implementing this method in your delegate:

    - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
    

    And you'll probably also need to implement these methods too:

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection;
    

    Using the async method tends to give a better user experience anyway so despite the extra complexity is worth doing even without the ability to do authentication.

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