Objective-C尝试下载来自简短网址的PDF

时间:2016-04-18 22:05:51

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

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

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

请检查有关处理重定向请求的AppleDocs

答案 2 :(得分:0)

尝试使用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 :(得分:0)

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