从重定向URL使用NSURLSessionDownloadTask下载pdf文件

时间:2014-11-17 13:36:01

标签: ios ios7 nsurlsessiondownloadtask

我正在创建一个用户登录网站并下载一些pdf文件的应用。

我能够使用URLSession成功登录网站。

现在我的问题在于下载文件。

该网站使用以下" http://www.someurl.com/getfile.asp?FILE=12345" 这显然是重定向到get url中嵌入的实际pdf文件,

尝试将NSURLSessionDownloadTask与url一起使用,但无法下载pdf文件。

有关如何从响应中获取实际URL以及下载文件的任何帮助吗?

这里我尝试了:注意我只是因为提问而改变了网址

//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]?@"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];

}

当我记录这个时,我得到null 的NSLog(@"%@",APPDIR);

1 个答案:

答案 0 :(得分:2)

您必须将路径组件附加到目录,而不是格式。试试这个

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

请记住,在使用stringByAppendingPathComponent:

时,您不需要使用'/'