Ссылки внутри Pdf на Webview не открываются в браузере на iPhone - PullRequest
0 голосов
/ 17 ноября 2011

Я проанализировал URL-адреса pdf и показал pdf в веб-представлении, но мои ссылки внутри веб-просмотров не открываются в браузере. Я не использовал CGPDFDocument. мой код прост :). Кто-нибудь может мне помочь. Я видел много подобных вопросов, но все используют Кварц.

код: -

@class AppDelegate_iPhone;
@interface PdfShowViewController : UIViewController<UIWebViewDelegate> {

    IBOutlet UIWebView *pdfWebview;
    AppDelegate_iPhone *appDelegate;
    NSMutableData *receivedData;
    IBOutlet UIActivityIndicatorView *myIndicator;
    IBOutlet UIProgressView *progress;

    NSURLRequest* DownloadRequest;
    NSURLConnection* DownloadConnection;

    long long bytesReceived;
    long long expectedBytes;
    IBOutlet UILabel *downloadLabel;

}

@property (nonatomic,retain) IBOutlet UILabel *downloadLabel;
@property (nonatomic,retain) IBOutlet UIWebView *pdfWebview;
@property (nonatomic,retain) IBOutlet UIActivityIndicatorView *myIndicator;
@property (nonatomic,retain) IBOutlet UIProgressView *progress;
@property (nonatomic,retain) NSMutableData *receivedData;
@property (nonatomic, readonly, retain) NSURLRequest* DownloadRequest;
@property (nonatomic, readonly, retain) NSURLConnection* DownloadConnection;
@property (nonatomic, retain, readwrite) NSURL *openURL;


-(IBAction)onTapBack;

@end



@implementation PdfShowViewController

@synthesize pdfWebview,myIndicator,progress,receivedData,DownloadRequest,DownloadConnection,downloadLabel,openURL;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];

    unsigned char byteBuffer[[receivedData length]];
    [receivedData getBytes:byteBuffer];
    NSLog(@"Data === %ld",receivedData);

    NSInteger receivedLen = [data length];
    bytesReceived = (bytesReceived + receivedLen);
    NSLog(@"received Bytes ==  %f",bytesReceived);

    if(expectedBytes != NSURLResponseUnknownLength) 
    {
        NSLog(@"Expected Bytes in if ==  %f",expectedBytes);
        NSLog(@"received Bytes in if ==  %f",bytesReceived);

        float value = ((float) (bytesReceived *100/expectedBytes))/100;
        NSLog(@"Value ==  %f",value);
        progress.progress=value;
    }

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [connection release];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    expectedBytes = [response expectedContentLength];
    NSLog(@"%f",expectedBytes);

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    [myIndicator stopAnimating];
    [myIndicator removeFromSuperview];
    [progress setHidden:YES];
    [downloadLabel setHidden:YES];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"iPhonePdf.pdf"];

    unsigned char byteBuffer[[receivedData length]];
    [receivedData getBytes:byteBuffer];

    [self.receivedData  writeToFile:pdfPath atomically:YES];

    [DownloadConnection release];

    //Now create Request for the file that was saved in your documents folder

    NSURL *url = [NSURL fileURLWithPath:pdfPath];

    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

    [pdfWebview setScalesPageToFit:YES];
    [pdfWebview loadRequest:requestObj];

}

-(BOOL)webView:(UIWebView *)webView1 shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *requestURL = [request URL];
    if(navigationType==UIWebViewNavigationTypeLinkClicked)
    {
        [[UIApplication sharedApplication] openURL:requestURL];
        return NO;
    }
    else
    {
        return YES;
    }
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    pdfWebview.delegate = self;

    appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];

    [downloadLabel setText:@"Downloading..."];
    [downloadLabel setHidden:NO];

    [myIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    myIndicator.hidesWhenStopped = YES;
    [myIndicator startAnimating];

    //  NSString *urlString = [appDelegate.currentBookPressed stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    NSString *urlString = [appDelegate.currentBookPressed stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

//  NSLog(@"The Url Stirng=======%@",urlString);

    NSURL *targetURL = [NSURL URLWithString:urlString];
    //NSLog(@"Trageted String ------======++++++++%@",targetURL);
    DownloadRequest = [NSURLRequest requestWithURL:targetURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:1200.0];
    DownloadConnection = [[NSURLConnection alloc] initWithRequest:DownloadRequest delegate:self];

    if (DownloadConnection) {
        receivedData = [[NSMutableData data]retain];
    }

    [pdfWebview setScalesPageToFit:YES];
    [pdfWebview loadRequest:DownloadRequest];


}

-(IBAction)onTapBack
{
    [self dismissModalViewControllerAnimated:YES];
}



@end

вот ссылка, которую я пытаюсь открыть, но не открываю: -

enter image description here

Ответы [ 2 ]

2 голосов
/ 18 ноября 2011

Нет, ссылки в файлах pdf, загруженных в UIWebView, не открываются, когда вы нажимаете их по умолчанию.

Вы можете пройти сложный путь и разобрать ссылки, используя Quartz, как показано в на этот другой пост, на который я ответил .

Или вместо загрузки pdf вы можете конвертировать загружаемый контент в html-файл? Это было бы проще, и тогда ссылки должны работать.

2 голосов
/ 17 ноября 2011

Вы должны использовать ниже метод делегата

-(BOOL)webView:(UIWebView *)webView1 shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
  NSURL *requestURL = [request URL]  ;
   if(navigationType==UIWebViewNavigationTypeLinkClicked)
   {
     [[UIApplication sharedApplication] openURL:requestURL];
     return NO;
   }
   else
   {
     return YES;
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...