保存UIWebView中的图片

尴尬的问题

壁纸保存不了,意义何在啊!!!!!!!!!!!!!!

.jpg

UIViewController.m

1.首先我们需要创建一个UIWebView并且添加长按手势

//新建webview
    _webview = [[UIWebView alloc]initWithFrame:self.view.bounds];
    _webview.delegate = self;
    [self.view addSubview:_webview];
    [self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.jianshu.com/p/c2e1cde8d119"]]];
//添加手势
    UnpreventableUILongPressGestureRecognizer *longPressRecognizer = [[UnpreventableUILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    longPressRecognizer.allowableMovement = 20;
    longPressRecognizer.minimumPressDuration = 1.0f;
    [_webview addGestureRecognizer:longPressRecognizer];```

###2.添加手势所要响应的手势

-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
CGPoint pt = [gestureRecognizer locationInView:self.webview];
//将手势触摸的点坐标转化成Html系统的点坐标
CGSize viewSize = [self.webview frame].size;
CGSize windowSize = [self.webview windowSize];
CGFloat f = windowSize.width / viewSize.width;
if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 5.0) {
pt.x = pt.x * f;
pt.y = pt.y * f;
} else {
// iOS4以及之前, document.elementFromPoint 方法并不存在,需要做一些转换
CGPoint offset = [self.webview scrollOffset];
pt.x = pt.x * f + offset.x;
pt.y = pt.y * f + offset.y;
}
//根据触摸的点,来获取触摸元素的Tag,以及Tag的Html属性。
[self openContextualMenuAt:pt];
}
}

###3.获取触摸元素的Tag,以及Tag的Html属性

NSString *path =[[NSBundle mainBundle] pathForResource:@"JSTools" ofType:@"js"];
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[_webview stringByEvaluatingJavaScriptFromString:jsCode];
// get the Tags at the touch location
NSString *tags = [_webview stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:@"MyAppGetHTMLElementsAtPoint(%li,%li);",(long)pt.x,(long)pt.y]];
NSString *tagsHREF = [_webview stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:@"MyAppGetLinkHREFAtPoint(%ld,%ld);",(long)pt.x,(long)pt.y]];
NSString *tagsSRC = [_webview stringByEvaluatingJavaScriptFromString: [NSString stringWithFormat:@"MyAppGetLinkSRCAtPoint(%ld,%ld);",(long)pt.x,(long)pt.y]];
NSLog(@"tags : %@",tags);
NSLog(@"href : %@",tagsHREF);
NSLog(@"src : %@",tagsSRC);
if (!_actionActionSheet) {
_actionActionSheet = nil;
}
_actionActionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
//图片a标签的href属性
_selectedLinkURL = @"";
//图片标签的Src属性
_selectedImageURL = @"";
if ([tags rangeOfString:@",IMG,"].location != NSNotFound) {
_selectedImageURL = tagsSRC;
if (_actionActionSheet.title == nil) {
_actionActionSheet.title = tagsSRC;
}
[_actionActionSheet addButtonWithTitle:@"保存图片"];
[_actionActionSheet addButtonWithTitle:@"复制图片"];
}
// If a link is pressed add image buttons.
if ([tags rangeOfString:@",A,"].location != NSNotFound){
_selectedLinkURL = tagsHREF;
_actionActionSheet.title = tagsHREF;
[_actionActionSheet addButtonWithTitle:@"打开图片链接"];
[_actionActionSheet addButtonWithTitle:@"复制图片连接"];
}
if (_actionActionSheet.numberOfButtons > 0) {
[_actionActionSheet addButtonWithTitle:@"Cancel"];
_actionActionSheet.cancelButtonIndex = (_actionActionSheet.numberOfButtons-1);
[_actionActionSheet showInView:_webview];
}

###4.action代理方法

if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"打开链接"]){
[_webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_selectedLinkURL]]];
}
else if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"复制链接"]){
[[UIPasteboard generalPasteboard] setString:_selectedLinkURL];
}
else if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"复制链接"]){
[[UIPasteboard generalPasteboard] setString:_selectedImageURL];
}
else if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"保存图片"]){
//方法1.比较浪费流量 //dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_selectedImageURL]]];
// UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
// });

// 方法2. 去缓存中去取 比较省流量
NSURLCache *cache =[NSURLCache sharedURLCache];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_selectedImageURL]];
NSData *imgData = [cache cachedResponseForRequest:request].data;
UIImage *images = [UIImage imageWithData:imgData];
UIImageWriteToSavedPhotosAlbum(images, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

###5.给webview实现一个category方法
  • (CGSize)windowSize
    {
    CGSize size;
    size.width = [[self stringByEvaluatingJavaScriptFromString:@"window.innerWidth"] integerValue];
    size.height = [[self stringByEvaluatingJavaScriptFromString:@"window.innerHeight"] integerValue];
    return size;
    }

  • (CGPoint)scrollOffset
    {
    CGPoint pt;
    pt.x = [[self stringByEvaluatingJavaScriptFromString:@"window.pageXOffset"] integerValue];
    pt.y = [[self stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"] integerValue];
    return pt;
    }```

6.jsTools.js里面实现的方法

//获取长按点处的tag
  function MyAppGetHTMLElementsAtPoint(x,y) {
    var tags = ",";
    var e = document.elementFromPoint(x,y);
    while (e) {
        if (e.tagName) {
            tags += e.tagName + ',';
        }
        e = e.parentNode;
    }
    return tags;
}
//获取长按tag的 Link
function MyAppGetLinkSRCAtPoint(x,y) {
    var tags = "";
    var e = document.elementFromPoint(x,y);
    while (e) {
        if (e.src) {
            tags += e.src;
            break;
        }
        e = e.parentNode;
    }
    return tags;
}
//获取长按tag的href
function MyAppGetLinkHREFAtPoint(x,y) {
    var tags = "";
    var e = document.elementFromPoint(x,y);
    while (e) {
        if (e.href) {
            tags += e.href;
            break;
        }
        e = e.parentNode;
    }
    return tags;
}```
###另外我们还需要实现一个UILongPressGestureRecognizer的私有api,具体看[Demo](https://github.com/gitless/HtmlSaveImage)吧
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 15,953评论 4 61
  • 清早上班途中,遇摊杂粮煎饼的老大爷,精瘦、利落,双目有神,颇有气节,断然拒绝一众人不加香菜、不加香菜、不加腌萝卜之...
    吹风吃面突然下雨阅读 309评论 0 0
  • 回顾前面文章:【目录】 《校园里的水池没鬼》第一章 《校园里的水池没鬼》第二章 6.谣言 法医从尸体情况分析后得出...
    苏宇城阅读 339评论 0 1
  • 小时候有爷爷奶奶宠爱我,家里最好的可以不给唯一的孙子但是要给我留;长大点爸爸妈妈宠爱我,不给姐姐们买的东西会给我买...
    孟园_29ec阅读 341评论 0 0

友情链接更多精彩内容