1.第一步在 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 獲取到圖片的URL
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *url = request.URL.absoluteString;
NSRange range = [url rangeOfString:@"sx:src="];
if (range.location != NSNotFound) {
NSInteger begin = range.location + range.length;
NSString *src = [url substringFromIndex:begin];
[self savePictureToAlbum:src];
return NO;
}
return YES;
}
2.第二步:根據URL 保存圖片
- (void)savePictureToAlbum:(NSString *)src
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"確定要保存到相冊嗎?" preferredStyle:UIAlertControllerStyleActionSheet];
[alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
NSURLCache *cache =[NSURLCache sharedURLCache];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:src]];
NSData *imgData = [cache cachedResponseForRequest:request].data;
UIImage *image = [UIImage imageWithData:imgData];
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}]];
[self presentViewController:alert animated:YES completion:nil];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
if (error != NULL){
[MBProgressHUD showError:@"下載失敗"];
}else{
[MBProgressHUD showSuccess:@"保存成功"];
}
}
3.關鍵之處在于如何獲取圖片的點擊事件
在這有兩種方法(1)使用 js添加點擊事件 NSString *onload = @"this.onclick = function() {"? ? ? ? "? window.location.href = 'sx:src=' +this.src;"? ? ? ? "};";? ? ? ? [imgHtml appendFormat:@"
",onload,width,height,detailImgModel.src];
第二種方法:采用js與源生交互