当视频文件存在并显示警报时,WebView 显示黑屏

Posted

技术标签:

【中文标题】当视频文件存在并显示警报时,WebView 显示黑屏【英文标题】:WebView shows black screen when video file exists and alert shows 【发布时间】:2014-07-02 08:25:02 【问题描述】:

我使用 UIWebView 来显示一个 url。它工作正常,但客户说要下载视频并将其保存到照片库中。我已经编写了从 UIWebView 下载视频并将其保存到照片库的代码。但是我写了一个条件,如果用户点击一个已经下载并保存到照片库的视频,显示一个文件已经保存的警报。然后我看到当这个消息同时显示时有黑色屏幕出现在与媒体播放器相同的视图上。所以我的问题是-如何控制或从网络视图中删除黑屏我已经通过重新加载相同的 UIWebView 删除了黑屏,但这不符合我的要求,所以请帮助我......请......请

这是我在 UIWebView 上显示 url 并保存视频文件的代码

#import "WebViewController.h"
#import "AppDelegate.h"
@interface WebViewController ()

  NSURL *theRessourcesURL;

@property (nonatomic, strong) NSString *lastURL;
@property(nonatomic,strong)MBProgressHUD *hud;
@end

@implementation WebViewController
@synthesize webView;


- (void)viewDidLoad

   [super viewDidLoad];

BOOL isLandscape = UIDeviceOrientationIsLandscape(self.interfaceOrientation);
BOOL isPortrait = UIDeviceOrientationIsPortrait(self.interfaceOrientation);
if(isLandscape)

    if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
    
        CGRect screenRect = [[UIScreen mainScreen] bounds];
        if (screenRect.size.height > 500)
        
            webView= [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, 568, 300)];
        
        else
        
            webView= [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, 480, 300)];
        
    
    else
    
        webView= [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, 1004, 748)];
    
    NSLog(@"isLandscape");

else if (isPortrait)

    if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
    
        CGRect screenRect = [[UIScreen mainScreen] bounds];
        if (screenRect.size.height > 500)
        
            webView= [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, 320, 548)];
        
        else
        
            webView= [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, 320, 460)];
        
    
    else
    
        webView= [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, 768, 984)];
    



[webView setDelegate:self];
webView.tag = 999;
for (UIView* subView in webView.subviews) 
    if ([subView isKindOfClass:[UIScrollView class]]) 
        currentScrollView = (UIScrollView *)subView;
        currentScrollView.delegate = (id) self;
    


//demo url
NSString *fullURL = @"http://demo.php.anuj.com/videoapp-t/home";



NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];

pull = [[PullToRefreshView alloc] initWithScrollView:currentScrollView];
[pull setDelegate:self];
pull.tag = 998;
[currentScrollView addSubview:pull];
[self.view addSubview:webView];



-(void)pullToRefreshViewShouldRefresh:(PullToRefreshView *)view 

  [(UIWebView *)[self.view viewWithTag:999] reload];


- (void)willAnimateRotationToInterfaceOrientation:  (UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration

BOOL isLandscape = UIDeviceOrientationIsLandscape(self.interfaceOrientation);
BOOL isPortrait = UIDeviceOrientationIsPortrait(self.interfaceOrientation);
if(isLandscape)

    if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
    
        CGRect screenRect = [[UIScreen mainScreen] bounds];
        if (screenRect.size.height > 500)
        
            webView.frame =CGRectMake(0, 20, 568, 300);
        
        else
        
           webView.frame =CGRectMake(0, 20, 480, 300);
        
    
    else
    
        webView.frame =CGRectMake(0, 20, 1004, 748);
    
    NSLog(@"isLandscape");

else if (isPortrait)

    if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
    
        CGRect screenRect = [[UIScreen mainScreen] bounds];
        if (screenRect.size.height > 500)
        
           webView.frame = CGRectMake(0, 20, 320, 548);
        
        else
        
            webView.frame =CGRectMake(0, 20, 320, 460);
        
    
    else
    
        webView.frame =CGRectMake(0, 20, 768, 984);
    

    
  

- (void)didReceiveMemoryWarning

   [super didReceiveMemoryWarning];

 

#pragma mark - webview

- (void)webViewDidStartLoad:(UIWebView *)webView 
   [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
   MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
   hud.mode = MBProgressHUDModeIndeterminate;
   hud.labelText = @"Loading...";




- (void)webViewDidFinishLoad:(UIWebView *)webView 
   [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
   [MBProgressHUD hideHUDForView:self.view animated:YES];
   [(PullToRefreshView *)[self.view viewWithTag:998] finishedLoading];
 

 - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error 
     AppDelegate *appdel=[[UIApplication sharedApplication]delegate];
     NetworkStatus remoteHostStatus = [appdel.reachability currentReachabilityStatus];
      if (remoteHostStatus == NotReachable)
      
           UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Anuj Demo"   message:@"Internet connection required. Please check connectivity to internet." delegate:nil   cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
          [alert show];
   
     else
    
      //        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Anuj Demo" message:@"Internet connection required. Please pull to refresh." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
      //          [alert show];
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [(PullToRefreshView *)[self.view viewWithTag:998] finishedLoading];

   

-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType

  if ( inType == UIWebViewNavigationTypeLinkClicked )
  
    theRessourcesURL = [inRequest URL];
    NSString *fileExtension = [theRessourcesURL pathExtension];

    if ([fileExtension isEqualToString:@"mp4"] || [fileExtension isEqualToString:@"mov"] || [fileExtension isEqualToString:@"m4v"])
    
        // Get the filename of the loaded ressource form the UIWebView's request URL

        NSString *filename = [theRessourcesURL lastPathComponent];
        NSLog(@"Filename: %@", filename);

        NSFileManager *filemanager=[NSFileManager defaultManager];

        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES);
        NSString *documentsDirectory= [paths objectAtIndex:0];

        NSString *path = [documentsDirectory stringByAppendingPathComponent:filename];

        BOOL success =[filemanager fileExistsAtPath:path];

        if (success ==TRUE) 
            UIAlertView *filenameAlert = [[UIAlertView alloc] initWithTitle:@"Reel Africa" message:[NSString stringWithFormat:@"The file %@ already exists.", filename] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [filenameAlert show];

    // Here if i reload webview then it works otherwise giving black screen on webview  like media player( [webview reload])

        
        else
        
            [self performSelector:@selector(saveVideoTOPhotoAlbum) withObject:nil afterDelay:0.2];
        
    
    else if([fileExtension isEqualToString:@"wmv"] || [fileExtension isEqualToString:@"3gp"] || [fileExtension isEqualToString:@"3G2"])
    
        UIAlertView *filenameAlert = [[UIAlertView alloc] initWithTitle:@"Anuj Demo" message:@"iPhone does not support this vedio format." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [filenameAlert show];
    
    NSString *tempString = [NSString stringWithFormat:@"%@",[inRequest URL]];
    if ([tempString rangeOfString:@"?ultima"].location != NSNotFound) 
        [[UIApplication sharedApplication] openURL:[inRequest URL]];
        return NO;
    
  
   return YES;
  

  -(void)saveVideoTOPhotoAlbum
   
  NSString *filename = [theRessourcesURL lastPathComponent];
  NSLog(@"Filename: %@", filename);
  // Get the path to the App's Documents directory
  NSString *docPath = [self documentsDirectoryPath];
  // Combine the filename and the path to the documents dir into the full path
  NSString *pathToDownloadTo = [NSString stringWithFormat:@"%@/%@", docPath, filename];
  // Load the file from the remote server
  NSData *tmp = [NSData dataWithContentsOfURL:theRessourcesURL];
  // Save the loaded data if loaded successfully
    if (tmp != nil) 
      NSError *error = nil;

      [tmp writeToFile:pathToDownloadTo options:NSDataWritingAtomic error:&error];

      // Write the contents of our tmp object into a file

      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
      NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
       NSString *getImagePath = [basePath stringByAppendingPathComponent:filename];
      printf(" \n\n\n-Video file == %s",[getImagePath UTF8String]);
      UISaveVideoAtPathToSavedPhotosAlbum ( getImagePath,self, @selector(video:didFinishSavingWithError: contextInfo:), nil);

     if (error != nil) 
        NSLog(@"Failed to save the file: %@", [error description]);
     else 
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        // Display an UIAlertView that shows the users we saved the file :)
        UIAlertView *filenameAlert = [[UIAlertView alloc] initWithTitle:@"Anuj Demo" message:[NSString stringWithFormat:@"The file %@ has been saved.", filename] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [filenameAlert show];
     
    



  - (void) video: (NSString *) videoPath didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
 

   NSLog(@"Finished saving video with error: %@", error);
   //Anuj here ****
  

- (NSString *)documentsDirectoryPath 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [paths objectAtIndex:0];
   return documentsDirectoryPath;



 @end

【问题讨论】:

如果你只想下载视频为什么要使用 webview ? 嗨,goodsp33d,webview 也用于显示给定 url 的页面并在其中播放视频并下载、保存....不仅仅是下载 【参考方案1】:

如果文件存在,则应返回 NO。试试看。

【讨论】:

嗨,技巧我已经用过,但仍然面临同样的问题。

以上是关于当视频文件存在并显示警报时,WebView 显示黑屏的主要内容,如果未能解决你的问题,请参考以下文章

WebView 显示黑屏

IOS Webview和视频

如果 webview 中没有互联网连接,iOS 会显示警报

如何解决在android开发中WebView在线播放视频黑屏啊?

Android WebView 中的 HTML5 视频不一致

webview 中的视频应在 android 中的 onShowCustomView() 方法上全屏显示