2011-09-14 4 views
0

인증을위한 자격 증명을 요구하는 사이트에서 docx, pdf, image, pptx 또는 파일을 다운로드하는 방법 자격 증명을 통과했지만 여전히 시도했습니다. nsdata의 데이터는 다른 것이지만 로컬에 생성 된 파일을 억지로 저장할 수 있기 때문에 모든 종류의 파일을 다운로드 할 수 있습니다. 다음과 같이docx, pdf, image, pptx 또는 인터넷에서 파일을 다운로드하는 방법

코드입니다 : 다른 파일 DownloadingFile.h

#import "MyAppDelegate.h" 

@interface DownloadingFile : NSObject 
{ 
    NSMutableData *webData; 
    NSMutableString *soapResults; 
    NSURLConnection *conn; 
    BOOL *elementFound; 
    BOOL isDoneParsing; 
    MyAppDelegate *mydelegate; 

    NSString *userCd,*passWord,*siteUrl; 

} 
@property (nonatomic ,retain) MyAppDelegate *mydelegate; 
-(void)buttonClicked; 
-(bool)getIsDone; 
@end 

DownloadingFile.m

#import "DownloadingFile.h" 
#import "iExploreAppDelegate.h" 

@implementation DownloadingFile 

@synthesize mydelegate; 

- (void)buttonClicked 
{ 
    mydelegate=(MyAppDelegate *)[[UIApplication sharedApplication] delegate]; 

    userCd=[[NSString alloc] initWithString:[mydelegate getUserId]]; 
    passWord=[[NSString alloc] initWithString:[mydelegate getPassword]]; 

    NSLog(@"In Downloading; "); 

    NSURL *url =[NSURL URLWithString:[@"http://abcdef.xyz.com/Docs/NewFolder/myFile.docx" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 

    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; 
     [req setValue:[NSString stringWithFormat:@"bytes=%ld-",0] forHTTPHeaderField:@"Range"]; 
     [req addValue: @"docx" forHTTPHeaderField:@"Content-Type"]; 
     [req setHTTPMethod:@"POST"]; 

     //---set the headers--- 
    conn = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES]; 

    if (conn) { 
     NSLog(@"connection done "); 

     webData = [[NSMutableData data] init]; 
    } 
} 


-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 
    if([challenge previousFailureCount] == 0) { 
     NSURLCredential *newCredential; 

     newCredential=[NSURLCredential credentialWithUser:userCd password:passWord persistence:NSURLCredentialPersistenceNone]; 
     NSLog(@"Crediantials done "); 
     [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge]; 
    } else { 
     [[challenge sender] cancelAuthenticationChallenge:challenge]; 
     NSError* error = [NSError errorWithDomain:@"SoapRequest" code:403 userInfo: [NSDictionary dictionaryWithObjectsAndKeys: @"Could not authenticate this request", NSLocalizedDescriptionKey,nil]]; 
     NSLog(@"Credentials are not valid"); 
     [mydelegate loginFailled:false]; 
    } 
} 



-(void) connection:(NSURLConnection *) connection 
didReceiveResponse:(NSURLResponse *) response { 
    //[webData setLength: 0]; 
} 

-(void) connection:(NSURLConnection *) connection 
    didReceiveData:(NSData *) data { 
    NSLog(@"recevied data %@",data); 
    webData=[NSMutableData dataWithData:data]; 
    [webData appendData:data]; 
} 

-(void) connection:(NSURLConnection *) connection 
    didFailWithError:(NSError *) error { 
    [webData release]; 
    [connection release]; 
} 
-(void) connectionDidFinishLoading:(NSURLConnection *) connection { 

    NSLog(@"Did Finish Loading done "); 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"FileName.docx"]; 

    [webData writeToFile:pdfPath atomically:YES]; 

    [connection release]; 

} 

답변

3

난 그냥 사용하여 테스트하는 간단한 응용 프로그램을 쓴 애플의 간단하고 강력한 솔루션 둘 다 NSURLConnection. 몇백 KB Word 및 PowerPoint 파일을 다운로드했습니다. 인증을 위해 .htaccess를 사용했습니다. 매력처럼 작동합니다. 다음은 관련 코드입니다. 좋은 작품 -

- (IBAction)clickedDownload:(id)sender { 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://myserver.com/downloadTest/testfile.pptx"]]; 
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; 
    [connection start]; 
} 

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
    // inform the user 
} 

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 
    if ([challenge previousFailureCount] == 0) {   
     NSURLCredential *newCredential; 
     newCredential = [NSURLCredential credentialWithUser:@"theUsername" 
                password:@"thePassword" 
               persistence:NSURLCredentialPersistenceNone]; 
     [[challenge sender] useCredential:newCredential 
       forAuthenticationChallenge:challenge]; 
    } else { 
     [[challenge sender] cancelAuthenticationChallenge:challenge]; 
     // inform the user that password is incorrect 
    } 
} 

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    receivedData = [[NSMutableData alloc] init]; 
} 

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [receivedData appendData:data]; 
} 

-(void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    NSURL *docDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 
    NSURL *filePath = [docDirectory URLByAppendingPathComponent:@"testfile.pptx"]; 
    [receivedData writeToURL:filePath atomically:YES]; 
    [receivedData release]; 
    connection = nil; 
} 

는 지금은 ~/라이브러리/응용 프로그램 지원/아이폰 시뮬레이터/4.3.2/응용 프로그램/[고유의 애플리케이션 코드]가/문서이 에있는 파일을 열어!

+0

감사합니다. 그것은 나를 위해 훌륭합니다! –

0

당신은 ASIHTTPRequest에 보일 것입니다에서 호출이은 buttonClicked에 . http://allseeing-i.com/ASIHTTPRequest/How-to-use

NSURL *url = [NSURL URLWithString:@"http://abcdef.xyz.com/Docs/NewFolder/myFile.docx"]; 
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
[request setUsername:@"username"]; 
[request setPassword:@"password"]; 
[request setDidFinishSelector:@selector(requestDone:)]; 
[request setDidFailSelector:@selector(requestWentWrong:)]; 

- (void)requestDone:(ASIHTTPRequest *)request 
{ 
    NSString *response = [request responseString]; 
} 

- (void)requestWentWrong:(ASIHTTPRequest *)request 
{ 
    NSError *error = [request error]; 
} 
관련 문제