NSURLErrorDomain error -1012

前端 未结 3 1642
予麋鹿
予麋鹿 2020-12-19 02:20

I need to parse a xml file from a password protected URL I tried the following

NSURLCredential *credential = [NSURLCredential credentialWithUser:@\"admin\"           


        
3条回答
  •  难免孤独
    2020-12-19 02:51

    While using a NSURLRequest to access a server, the delegate methods of NSURLConnection provides a way to be notified when an authentication is challenged.

    This below sample will show one approach to handle URLs that asks credentials.

    - (void)CallPasswordProtectedWebService
    {
     NSURL *url = [NSURL URLWithString:@"your url"];
     NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    }
    
    //when server asks the credentials this event will fire
    
     - (void)connection:(NSURLConnection *)connection 
      didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
    {
    
     if ([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential;
        newCredential=[NSURLCredential credentialWithUser:@"username"                                               password:@"password"                                              persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];
    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
    }
    
    //when connection succeeds this event fires
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
     NSLog(@"Successfuly connected ");  
    
    }
    
    //when connection fails the below event fires 
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
     NSLog(@"connection failed");
    
    }
    

    Hope this helps

提交回复
热议问题