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

时间:2014-07-02 08:25:03

标签: ios objective-c uiwebview

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

1 个答案:

答案 0 :(得分:0)

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