2014-11-17 3 views
0

사용자가 웹 사이트에 로그인하여 일부 pdf 파일을 다운로드하는 앱을 만들고 있습니다.리디렉션 URL에서 NSURLSessionDownloadTask를 사용하여 pdf 파일 다운로드

URLSession을 사용하여 사이트에 성공적으로 로그인 할 수있었습니다.

이제 내 문제는 파일을 다운로드하는 것입니다.

이 웹 사이트와 URL을 사용하는 다음 "http://www.someurl.com/getfile.asp?FILE=12345"가져 오기 URL에 포함 된 실제 pdf 파일로 이 명확하게 리디렉션,

가 URL로 NSURLSessionDownloadTask을 사용하려고하지만, pdf 파일을 다운로드 할 수 있습니다 .

응답에서 실제 URL로 이동하여 파일을 다운로드하는 방법에 대한 도움이 필요합니까?

내가 시도 여기에 무엇을 : 나는 NSLog ("%의 @", APPDIR @) 널 받기를 로그인 할 때 난 그냥 질문

//1 create NSURL to the login page 
NSURL *tempURL = [NSURL URLWithString:@"http://www.someurl.com/login.asp"]; 
// 2 create Mutable request with header and username and password 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:tempURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1.0]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; 
//this is hard coded based on your suggested values, obviously you'd probably need to make this more dynamic based on your application's specific data to send 
NSString *postString = @"userid=abcdef&passwd=123456789&submit=Login"; 

NSData *data = [postString dataUsingEncoding:NSUTF8StringEncoding]; 
[request setHTTPBody:data]; 
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[data length]] forHTTPHeaderField:@"Content-Length"]; 
//3 Create NSURLSession to login 
NSURLSession *session = [NSURLSession sharedSession]; 
//4 Create Session Data task to download the html page required 
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
             { 

              NSURL *fileURL = [NSURL URLWithString:@"http://www.someurl.com/file.asp?File=20904"]; 

              NSURLSessionDownloadTask *pdfDownload = [[NSURLSession sharedSession] downloadTaskWithURL:fileURL completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) { 

               NSLog(@"%@", location.description); 

               NSFileManager *fileManager = [NSFileManager defaultManager]; 
               NSError *error1; 

               //getting application's document directory path 
               NSArray * tempArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
               NSString *docsDir = [tempArray objectAtIndex:0]; 

               //adding a new folder to the documents directory path 
               NSString *appDir = [docsDir stringByAppendingPathComponent:@"/PDFs/"]; 

               //Checking for directory existence and creating if not already exists 
               if(![fileManager fileExistsAtPath:appDir]) 
               { 
                [fileManager createDirectoryAtPath:appDir withIntermediateDirectories:NO attributes:nil error:&error1]; 
               } 

               //retrieving the filename from the response and appending it again to the path 
               //this path "appDir" will be used as the target path 
               appDir = [appDir stringByAppendingFormat:@"/%@",[[pdfDownload response] suggestedFilename]]; 

               //checking for file existence and deleting if already present. 
               if([fileManager fileExistsAtPath:appDir]) 
               { 
                NSLog([fileManager removeItemAtPath:appDir error:&error1][email protected]"deleted":@"not deleted"); 
               } 

               //moving the file from temp location to app's own directory 
               BOOL fileCopied = [fileManager moveItemAtPath:[location path] toPath:appDir error:&error1]; 
               NSLog(fileCopied ? @"Yes" : @"No"); 
               NSLog(@"%@",appDir); 
              }]; 

              [pdfDownload resume]; 

             }]; 
[postDataTask resume]; 

} 

요청의 URL을 변경합니다;

+0

stringByAppendingPathComponent:을 사용하는 경우이

appDir = [appDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",[response suggestedFilename]]]; 

을 시도하고 당신은 '/'를 사용하지 않아도 기억 해요. 'appDir = [appDir stringByAppendingPathComponent : @ "myFile.pdf"];' –

+0

P. 'stringByAppendingPathComponent'를 사용할 때 '/'를 사용할 필요가 없습니다. –

+1

그리고'pdfDownload'에 액세스하지 않고 단순히 블록의 매개 변수처럼'response' 만 사용해야합니다. –

답변

2

형식이 아닌 디렉터리에 경로 구성 요소를 추가해야합니다. 당신은 당신이 디렉토리가 아닌 형식으로 경로 구성 요소를 추가해야