UIWebView通过添加手势JS交互保存图片

demo 地址

https://github.com/daijuqing/UIWebviewCopyPic


if(_longGes==nil) {

_longGes= [[UILongPressGestureRecognizeralloc]initWithTarget:selfaction:@selector(getPic:)];

_longGes.minimumPressDuration=1;

_longGes.delegate=self;

_longGes.allowableMovement=15;

_longGes.numberOfTouchesRequired=1;

_longGes.cancelsTouchesInView=true;

[_webviewaddGestureRecognizer:_longGes];

}



方法

-(void)getPic:(UILongPressGestureRecognizer*)recognizer

{

if(recognizer.state!=UIGestureRecognizerStateBegan) {

return;

}

CGPointtouchPoint = [recognizerlocationInView:self.webview];

NSString*imgURL = [NSStringstringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];

NSString*urlToSave = [self.webviewstringByEvaluatingJavaScriptFromString:imgURL];

_imgURL= urlToSave;

if(urlToSave.length==0) {

return;

}

[selfhandleLongTouch];

}

- (void)handleLongTouch {

NSLog(@"%@",_imgURL);

UIActionSheet* sheet =[[UIActionSheetalloc]initWithTitle:nildelegate:selfcancelButtonTitle:@"取消"destructiveButtonTitle:nilotherButtonTitles:@"保存图片",nil];

sheet.cancelButtonIndex= sheet.numberOfButtons-1;

[sheetshowInView:[UIApplicationsharedApplication].keyWindow];

}

- (void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

if(actionSheet.numberOfButtons-1== buttonIndex) {

return;

}

NSString* title = [actionSheetbuttonTitleAtIndex:buttonIndex];

if([titleisEqualToString:@"保存图片"]) {

if(_imgURL) {

NSLog(@"imgurl = %@",_imgURL);

}

NSURL*url = [NSURLURLWithString:_imgURL];

NSURLSessionConfiguration* configuration = [NSURLSessionConfigurationdefaultSessionConfiguration];

NSURLSession*session = [NSURLSessionsessionWithConfiguration:configurationdelegate:selfdelegateQueue:[NSOperationQueuenew]];

NSURLRequest*imgRequest = [NSURLRequestrequestWithURL:urlcachePolicy:NSURLRequestReturnCacheDataElseLoadtimeoutInterval:30.0];

NSURLSessionDownloadTask*task = [sessiondownloadTaskWithRequest:imgRequestcompletionHandler:^(NSURL*_Nullablelocation,NSURLResponse*_Nullableresponse,NSError*_Nullableerror) {

if(error) {

return;

}

NSData* imageData = [NSDatadataWithContentsOfURL:location];

dispatch_async(dispatch_get_main_queue(), ^{

UIImage* image = [UIImageimageWithData:imageData];

UIImageWriteToSavedPhotosAlbum(image,self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);

});

}];

[taskresume];

}

}

- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo

{

if(error){

NSLog(@"Error");

//[self showAlert:SNS_IMAGE_HINT_SAVE_FAILE];

}else{

NSLog(@"OK");

UIAlertView*alertView = [[UIAlertViewalloc]initWithTitle:@"提醒"message:@"保存成功!"delegate:nilcancelButtonTitle:@"确定"otherButtonTitles:nil,nil];

[alertViewshow];

}

}

你可能感兴趣的:(UIWebView通过添加手势JS交互保存图片)