下载PDF版iOS

时间:2012-09-06 00:11:59

标签: ios pdf nsurlconnection nsdata downloading

我无法从网络链接下载多个PDF文件。我的代码可以在Web服务器上找到这些文件,但它只下载大约360个字节。每个文件大约2-3 MB,读取时产生%PDF,据我所知,这是PDF的起始字节。

此代码发生的情况是传递一个字符串,然后从plist文件访问字典,该文件刚从包含PDF文件的同一Web服务器下载。然后,该字符串将获取Web服务器上的PDF的实际名称,并通过NSURLConnection下载到NSData对象。最后,它被写入Apps Documents目录。

任何帮助都会很棒!

- (void)fileToDownload:(NSString *)stringToPDFName {

NSString *downloadfile = [[masterDictionary objectForKey:@"PDF Dictionary"] objectForKey:stringToPDFName];
NSLog(@"downloadFile: %@",downloadfile);

NSString *pathToFile = [NSString stringWithFormat:@"%@%@.pdf",staticURLToPDF,downloadfile];
NSLog(@"pathToFile: %@",pathToFile);
NSError *error;

if ([listOfPDFsAlreadyDownloaded containsObject:pathToFile]) {
    NSLog(@"File Already Downloaded From New List: %@", [pathToFile stringByReplacingOccurrencesOfString:staticURLToPDF withString:@""]);
} else {
    //download new file
    NSString *urlString = [[staticURLToPDF stringByAppendingPathComponent:downloadfile] stringByAppendingPathExtension:@".pdf"];

    NSData *pdfDownloading = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] returningResponse:NULL error:&error];


    NSLog(@"pdfDownloading Data: %@, Error: %@", pdfDownloading,error);

    BOOL written = [pdfDownloading writeToFile:[NSString stringWithFormat:@"%@/POGs/%@.pdf",documentsDirectory,downloadfile] atomically:YES];

    NSLog(@"FileDownloading %@/POGs/%@.pdf",documentsDirectory,downloadfile);

    if (written) {
        NSLog(@"Success");
        downloadedDocuments++;
    } else {
        NSLog(@"File Didn't Save");
    }
    [listOfPDFsAlreadyDownloaded addObject:pathToFile];
    NSLog(@"File to Download: %@",[pathToFile stringByReplacingOccurrencesOfString:staticURLToPDF withString:@""]);
    NSLog(@"%i documentsDownloaded",downloadedDocuments);
}

}

1 个答案:

答案 0 :(得分:0)

您希望使用NSURLSession,尤其是NSURLSessionDownloadTask来下载文件。

我建议从Apple的官方文档开始: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html

请不要做同步请求。网络本质上很慢,因此任务应该始终异步发生。