如何在webview上缓存图像?

时间:2013-07-01 08:29:28

标签: ios objective-c caching uiwebview fgallery

我在UIViewController中有一个UIWebView。我正在通过此功能加载UIWebView的内容:

 - (void)loadHTMLString:(NSString *)html {
    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSURL *baseURL = [NSURL fileURLWithPath:path];
    [self.webView loadHTMLString:html baseURL:baseURL];
}

如果我的内容包含许多图片,我会通过FGallery(https://github.com/gdavis/FGallery-iPhone)创建一个图库。当我第一次打开UIViewController时,我正在我的UIWebView中加载图像和文本。我关闭一个应用程序并关闭网络。然后我打开我的应用程序并打开一个UIViewController。我正在从缓存中加载我的UIWebView。但我有一个问题。如果我打开图库直到关闭网络,画廊的封面不会从缓存加载,但加载了库中的所有图像。如果我在关闭网络之前没有打开图库,则会从缓存中加载图库的封面。画廊的封面和画廊的第一张图片是一样的。

如果我打开一个图库,为什么不加载图库的封面?

1 个答案:

答案 0 :(得分:1)

可能是webview的合适答案

- (BOOL)webView:(UIWebView*)webViewRef shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    if (navigationType == UIWebViewNavigationTypeLinkClicked) 
    {
        NSURL *URL = [request URL]; //Get the URL
        if ( [[URL scheme] isEqualToString:@"objc"] ) {
            webView = webViewRef;
            SEL method = NSSelectorFromString( [URL host] );
            if ([self respondsToSelector:method])
            {
                [self performSelector:method withObject:nil afterDelay:0.1f];
            }
            return NO;
        }
    }
   return YES;
}
-(void)takePicture
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.delegate = self;
    id delegate = [[UIApplication sharedApplication] delegate];
    [[delegate viewController] presentModalViewController:imagePicker animated:YES];
    [imagePicker release];
}

#pragma mark - Image Picker

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    NSData *flatImage = UIImageJPEGRepresentation(image, 0.1f);
    NSString *image64 = [flatImage base64EncodedString];
    NSString *js = [NSString stringWithFormat: @"processImage('data:image/jpeg;base64,%@')", image64];
    [webView stringByEvaluatingJavaScriptFromString:js];
    [picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    //cancel was hit inside of the camera view
    [picker dismissModalViewControllerAnimated:YES];
}