[掌眼]IOS UIWebView Long press save image 長按圖片儲存到手機

來源:互聯網
上載者:User

標籤:des   style   class   blog   c   code   

具體效果可下載“掌眼”古玩江湖進行測試:http://bbs.guwanch.com

ViewController.h

@interface ViewController : CDVViewController<UIActionSheetDelegate>{    NSTimer *_timer;    // 用於UIWebView儲存圖片    int _gesState;      // 用於UIWebView儲存圖片    NSString *_imgURL;  // 用於UIWebView儲存圖片}static NSString* const kTouchJavaScriptString=@"document.ontouchstart=function(event){x=event.targetTouches[0].clientX;y=event.targetTouches[0].clientY;document.location=\"myweb:touch:start:\"+x+\":\"+y;};\document.ontouchmove=function(event){x=event.targetTouches[0].clientX;y=event.targetTouches[0].clientY;document.location=\"myweb:touch:move:\"+x+\":\"+y;};\document.ontouchcancel=function(event){document.location=\"myweb:touch:cancel\";};\document.ontouchend=function(event){document.location=\"myweb:touch:end\";};";// 用於UIWebView儲存圖片enum{    GESTURE_STATE_NONE = 0,    GESTURE_STATE_START = 1,    GESTURE_STATE_MOVE = 2,    GESTURE_STATE_END = 4,    GESTURE_STATE_ACTION = (GESTURE_STATE_START | GESTURE_STATE_END),};

 

ViewController.m

// 網頁載入完成時觸發#pragma mark UIWebDelegate implementation- (void)webViewDidFinishLoad:(UIWebView*)theWebView{    // Black base color for background matches the native apps    theWebView.backgroundColor = [UIColor blackColor];        NSString *title = [theWebView stringByEvaluatingJavaScriptFromString:@"document.title"];    self.navigationItem.title = [self isBlank:title]?@"掌眼":title;        // 當iOS版本大於7時,向下移動20dp    if (!IOS7) { }        // 防止記憶體流失    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];        // 響應touch事件,以及獲得點擊的座標位置,用於儲存圖片    [theWebView stringByEvaluatingJavaScriptFromString:kTouchJavaScriptString];        return [super webViewDidFinishLoad:theWebView];}// 功能:UIWebView響應長按事件-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)_request navigationType:(UIWebViewNavigationType)navigationType {    NSString *requestString = [[_request URL] absoluteString];    NSArray *components = [requestString componentsSeparatedByString:@":"];    if ([components count] > 1 && [(NSString *)[components objectAtIndex:0]                                   isEqualToString:@"myweb"]) {        if([(NSString *)[components objectAtIndex:1] isEqualToString:@"touch"])        {            //NSLog(@"you are touching!");            //NSTimeInterval delaytime = Delaytime;            if ([(NSString *)[components objectAtIndex:2] isEqualToString:@"start"])            {                /*                 @需延時判斷是否響應頁面內的js...                 */                _gesState = GESTURE_STATE_START;                NSLog(@"touch start!");                                float ptX = [[components objectAtIndex:3]floatValue];                float ptY = [[components objectAtIndex:4]floatValue];                NSLog(@"touch point (%f, %f)", ptX, ptY);                                NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).tagName", ptX, ptY];                NSString * tagName = [self.webView stringByEvaluatingJavaScriptFromString:js];                _imgURL = nil;                if ([tagName isEqualToString:@"IMG"]) {                    _imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", ptX, ptY];                }                if (_imgURL) {                    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handleLongTouch) userInfo:nil repeats:NO];                }            }            else if ([(NSString *)[components objectAtIndex:2] isEqualToString:@"move"])            {                //**如果touch動作是滑動,則取消hanleLongTouch動作**//                _gesState = GESTURE_STATE_MOVE;                NSLog(@"you are move");            }        }        else if ([(NSString*)[components objectAtIndex:2]isEqualToString:@"end"]) {            [_timer invalidate];            _timer = nil;            _gesState = GESTURE_STATE_END;            NSLog(@"touch end");        }        return NO;    }    return [super webView:webView shouldStartLoadWithRequest:_request navigationType:navigationType];}// 功能:如果點擊的是圖片,並且按住的時間超過1s,執行handleLongTouch函數,處理圖片的儲存操作。- (void)handleLongTouch {    NSLog(@"%@", _imgURL);    if (_imgURL && _gesState == GESTURE_STATE_START) {        UIActionSheet* sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"儲存到手機", nil];        sheet.cancelButtonIndex = sheet.numberOfButtons - 1;        [sheet showInView:[UIApplication sharedApplication].keyWindow];    }}// 功能:儲存圖片到手機- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {    if (actionSheet.numberOfButtons - 1 == buttonIndex) {        return;    }    NSString* title = [actionSheet buttonTitleAtIndex:buttonIndex];    if ([title isEqualToString:@"儲存到手機"]) {        if (_imgURL) {            NSLog(@"imgurl = %@", _imgURL);        }        NSString *urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:_imgURL];        NSLog(@"image url = %@", urlToSave);                NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlToSave]];        UIImage* image = [UIImage imageWithData:data];                //UIImageWriteToSavedPhotosAlbum(image, nil, nil,nil);        NSLog(@"UIImageWriteToSavedPhotosAlbum = %@", urlToSave);        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);    }}// 功能:顯示對話方塊-(void)showAlert:(NSString *)msg {    NSLog(@"showAlert = %@", msg);    UIAlertView *alert = [[UIAlertView alloc]                          initWithTitle:@"提示"                          message:msg                          delegate:self                          cancelButtonTitle:@"確定"                          otherButtonTitles: nil];    [alert show];}// 功能:顯示圖片儲存結果- (void)image:(UIImage *)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo{    if (error){        NSLog(@"Error");        [self showAlert:@"儲存失敗..."];    }else {        NSLog(@"OK");        [self showAlert:@"儲存成功!"];    }}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.