Objective-C 正在尝试下载来自 url 短片的 PDF

Objective-C Trying to download PDF that is from a short url

我一直在尝试在不首先加载 Web 视图并从中获取 absoluteString 的情况下让它工作,以便我可以下载 URL。我尝试了很多简短的 URL 解决方案,但它们从未完全加载 URL。他们总是给我 URL,但不是最终 url,也不是 PDF url。任何帮助都会很棒。我试图在应用程序首次打开或检查更新时下载 PDF,但当时它只是短 url,我必须等到调用网络视图才能获得完整 url 能够提前下载 PDF。

您下载 PDF,就像下载任何其他文件一样。

看看NSURLDownload

- (void)startDownloadingURL:sender
{
    // Create the request.
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/index.html"]
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                             timeoutInterval:60.0];

    // Create the download with the request and start loading the data.
NSURLDownload  *theDownload = [[NSURLDownload alloc] initWithRequest:theRequest delegate:self];
    if (!theDownload) {
        // Inform the user that the download failed.
    }
}

- (void)download:(NSURLDownload *)download decideDestinationWithSuggestedFilename:(NSString *)filename
{
    NSString *destinationFilename;
    NSString *homeDirectory = NSHomeDirectory();

    destinationFilename = [[homeDirectory stringByAppendingPathComponent:@"Desktop"]
        stringByAppendingPathComponent:filename];
    [download setDestination:destinationFilename allowOverwrite:NO];
}


- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
{
    // Dispose of any references to the download object
    // that your app might keep.
    ...

    // Inform the user.
    NSLog(@"Download failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)downloadDidFinish:(NSURLDownload *)download
{
    // Dispose of any references to the download object
    // that your app might keep.
    ...

    // Do something with the data.
    NSLog(@"%@",@"downloadDidFinish");
}

请检查 AppleDocs 关于处理重定向请求的信息。

尝试使用 afnetworking 将 pdf 文件下载到服务器

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://letuscsolutions.files.wordpress.com/2015/07/five-point-someone-chetan-bhagat_ebook.pdf"]];
    [request setTimeoutInterval:120];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    NSString *pdfName = @"2.zip";

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:pdfName];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
     };

        dispatch_async(dispatch_get_main_queue(), ^{

             NSLog(@"Download = %f", (float)totalBytesRead / totalBytesExpectedToRead);
            NSLog(@"total bytesread%f",(float)totalBytesRead );
            NSLog(@"total bytesexpected%lld",totalBytesExpectedToRead );

        });


    }];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Successfully downloaded file to %@", path);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

    [operation start];

这是一种使用 UIDocumentInteractionController 从 URL 打开 pdf 文件的方法:

- (void)openURL:(NSURL*)fileURL{
    //Request the data from the URL
    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:fileURL completionHandler:^(NSData *data, NSURLResponse *response,NSError *error){
        if(!error){
            //Save the document in a temporary file
            NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[response suggestedFilename]];
            [data writeToFile:filePath atomically:YES];
            //Open it with the Document Interaction Controller
            _docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
            _docController.delegate = self;
            _docController.UTI = @"com.adobe.pdf";
            [_docController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];

        }
    }] resume];

}

和myViewController.h:

@interface myViewController : UIViewController <UIDocumentInteractionControllerDelegate>

@property UIDocumentInteractionController *docController;