0

我在从网络链接下载多个 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);
}

}

4

1 回答 1

0

您想使用NSURLSession,尤其是NSURLSessionDownloadTask下载文件。

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

请不要做同步请求。网络本来就很慢,所以任务应该总是异步发生。

于 2016-05-26T08:47:08.090 回答