I want to download a PDF file from my server and save it to the documents directory. I am able to do this using NSData but then the file in the documents directory is not a PDF: it's an NSData object. Is there any way to download and save a straight PDF file?
A:
NSData *pdfData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:@"http://…"]];
[pdfData writeToFile:@"…" atomically:YES];
This does not work?
zoul
2010-10-08 08:30:58
No. When I run this (on the simulator) and then check the documents directory the file cannot be opened in preview. I'm assuming that it is being save as an NSData object and not as a pdf file.
John
2010-10-08 08:55:18
There is no “saving as NSData”. When you call `writeToFile:`, the object simply writes its contents to the specified file. Is the extension `.pdf`? Did you try to peek at the file contents?
zoul
2010-10-08 09:10:44
Ok, the filename is 1.pdf. I tried to open the file with preview but it doesn't work. OSX doesn't recognise the file.
John
2010-10-08 09:20:38
I just tried the code, works fine for me. Make sure that the PDF is there on the server, check the downloaded file size, check the file contents using an editor (TextMate or whatever) and post the code you’re using.
zoul
2010-10-08 09:28:48
If I select the file and get info it tells me the following:kind: document
John
2010-10-08 09:30:31
Sorry, I just worked it out. Even though I had the filename as 1.pdf I needed to add another pdf. NSString *filePath = [resourceDocPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pdf", filename]];
John
2010-10-08 09:33:02