保存UIWebView中的圖片

尷尬的問題

壁紙保存不了,意義何在啊!!!!!!!!!!!!!!

.jpg

UIViewController.m

1.首先我們需要創(chuàng)建一個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.itdecent.cn/p/c2e1cde8d119"]]];
//添加手勢
    UnpreventableUILongPressGestureRecognizer *longPressRecognizer = [[UnpreventableUILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    longPressRecognizer.allowableMovement = 20;
    longPressRecognizer.minimumPressDuration = 1.0f;
    [_webview addGestureRecognizer:longPressRecognizer];```

###2.添加手勢所要響應(yīng)的手勢

-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
CGPoint pt = [gestureRecognizer locationInView:self.webview];
//將手勢觸摸的點坐標轉(zhuǎn)化成Html系統(tǒng)的點坐標
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 方法并不存在,需要做一些轉(zhuǎn)換
CGPoint offset = [self.webview scrollOffset];
pt.x = pt.x * f + offset.x;
pt.y = pt.y * f + offset.y;
}
//根據(jù)觸摸的點,來獲取觸摸元素的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:@"復(fù)制圖片"];
}
// If a link is pressed add image buttons.
if ([tags rangeOfString:@",A,"].location != NSNotFound){
_selectedLinkURL = tagsHREF;
_actionActionSheet.title = tagsHREF;
[_actionActionSheet addButtonWithTitle:@"打開圖片鏈接"];
[_actionActionSheet addButtonWithTitle:@"復(fù)制圖片連接"];
}
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:@"復(fù)制鏈接"]){
[[UIPasteboard generalPasteboard] setString:_selectedLinkURL];
}
else if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"復(fù)制鏈接"]){
[[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實現(xiàn)一個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里面實現(xiàn)的方法

//獲取長按點處的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;
}```
###另外我們還需要實現(xiàn)一個UILongPressGestureRecognizer的私有api,具體看[Demo](https://github.com/gitless/HtmlSaveImage)吧
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,407評論 4 61
  • 清早上班途中,遇攤雜糧煎餅的老大爺,精瘦、利落,雙目有神,頗有氣節(jié),斷然拒絕一眾人不加香菜、不加香菜、不加腌蘿卜之...
    吹風(fēng)吃面突然下雨閱讀 305評論 0 0
  • 回顧前面文章:【目錄】 《校園里的水池沒鬼》第一章 《校園里的水池沒鬼》第二章 6.謠言 法醫(yī)從尸體情況分析后得出...
    蘇宇城閱讀 339評論 0 1
  • 小時候有爺爺奶奶寵愛我,家里最好的可以不給唯一的孫子但是要給我留;長大點爸爸媽媽寵愛我,不給姐姐們買的東西會給我買...
    孟園_29ec閱讀 331評論 0 0

友情鏈接更多精彩內(nèi)容