kupilot
kupilot

Reputation: 504

Downloading a pdf file using NSURLSessionDownloadTask from redirect URL

I'm making an app where the user login to a website and download some pdf files.

i was able to login successfully into the site using URLSession.

Now my problem is with the download of the file.

The website uses a url with the following "http://www.someurl.com/getfile.asp?FILE=12345" this clearly a redirect to the actual pdf file embedded in the get url,

tried to use NSURLSessionDownloadTask with the url but couldn't download the pdf file.

Any help in how to get to the actual URL from the response and download the file?

here what i tried: Note i changed the urls just for asking the question

//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];

}

When i log this i get null NSLog(@"%@",appDir);

Upvotes: 1

Views: 1481

Answers (1)

Francesco Frascà
Francesco Frascà

Reputation: 186

You have to append a path component to the directory, not a format. Try this

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

And remember that you don't need to use '/' when you are using stringByAppendingPathComponent:

Upvotes: 2

Related Questions