Я пару дней боролся с проблемой NSURLConnection в моем приложении.Мне нужно подключиться к серверу (вызывая getPdfFromServerAtIndex), используя протокол ftp, чтобы получить объект (pdf-страницу, но это не имеет значения!).Когда я пытаюсь подключиться к URL-адресу http, у меня нет проблем.То же самое для http-URL, запрашивающего аутентификацию, все мои делегированные методы вызываются.
Но когда я использую URL, показанный ниже, построенный с использованием протокола ftp, методы делегирования, такие как didReceiveAuthenticationChallenge, canAuthenticateAgainstProtectionSpace, никогда не вызывают.
Когда цикл while (! Закончен), циклВызывается только метод connectionShouldUseCredentialStorage, а затем метод didFailWithError выдает ошибку «Ошибка подключения! Ошибка - у вас нет прав доступа к запрошенному ресурсу. ftp: //ftp.www.thephilosopher.org/»,Тем не менее, когда я пытаюсь вставить URL-адрес ftp в мой браузер, меня просят ввести имя пользователя и пароль.
Есть идеи, почему при использовании протокола ftp я не могу аутентифицироваться и получить доступ к серверу?
-(void)getPdfFromServerAtIndex:(NSUInteger)index{
// Create the request.
// Set finished to false
finished = FALSE;
NSString *pageNumber = [NSString stringWithFormat:@"ftp://ftp.www.thephilosopher.org/Iphone/0%i.pdf",index+1];
NSURL* nsurl = [NSURL URLWithString:pageNumber];
urlReq = [[NSMutableURLRequest alloc] initWithURL:nsurl];
BOOL canHandle = [NSURLConnection canHandleRequest:urlReq];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:urlReq delegate:self];
if (conn && canHandle) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
NSLog(@"Connection Failed!");
}
while(!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
finished = TRUE;
// receivedData is declared as a method instance elsewhere
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
// release the connection, and the data object
[connection release];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace*)tmpProtectionSpace {
// Check the NSURLProtectionSpace
return YES;}
-(NSURLRequest *)connection:(NSURLConnection *)inConnection willSendRequest:(NSURLRequest *)inRequest redirectResponse:(NSURLResponse *)inRedirectResponse{
if(inRedirectResponse){
NSMutableURLRequest *r = [[urlReq mutableCopy] autorelease]; // original request
[r setURL: [inRequest URL]];
return r;
} else {
return inRequest;
}
}
-(BOOL)connectionShouldUseCredentialStorage:(NSURLConnection*)connection{
NSLog(@"connectionShouldUseCredentialStorage");
return YES;
}
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
if([challenge previousFailureCount] == 0) {
NSURLCredential *newCredential;
newCredential=[NSURLCredential credentialWithUser:@"XXXX" password:@"XXXXX" persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];}
else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
NSLog(@"Bad Username Or Password");}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
// release the connection, and the data object
[connection release];
// receivedData is declared as a method instance elsewhere
[receivedData release];
// inform the user
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"Data received");
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"Response received");
[receivedData setLength:0];
}