【问题标题】:Objective-C Trying to download PDF that is from a short urlObjective-C 尝试从短网址下载 PDF
【发布时间】:2016-08-10 20:21:19
【问题描述】:

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

【问题讨论】:

    标签: objective-c pdf redirect download short-url


    【解决方案1】:

    这是一种使用 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;
    

    【讨论】:

      【解决方案2】:

      尝试使用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];
      

      【讨论】:

        【解决方案3】:

        请查看AppleDocs 处理重定向请求。

        【讨论】:

          【解决方案4】:

          您下载 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");
          }
          

          【讨论】:

          • 我试过这个,它总是以错误结束,因为它没有完成重定向 URL 以获取 PDF 的实际 URL。我现在这样做的方式是等待 Web 视图加载,以便它完成重定向并执行 webView.request.URL.absoluteString。问题是,当视图加载 PDF 时,PDF 现在会下载。我希望在应用程序打开时下载 PDF,因此我需要应用程序打开时重定向的完整 URL。
          猜你喜欢
          • 1970-01-01
          • 2016-01-03
          • 2012-02-24
          • 2020-12-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多