美文网首页iOS开发
iOS WKWebView H5界面调用OC方法 保存图片至相册

iOS WKWebView H5界面调用OC方法 保存图片至相册

作者: 浅笑回忆念旧时 | 来源:发表于2019-12-26 14:53 被阅读0次

话不多说,直接上代码

   WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];

    WKUserContentController *userController = [[WKUserContentController alloc] init];

    configuration.userContentController= userController;

    wevView = [[WKWebView alloc]initWithFrame: CGRectMake(0,NAVBAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-NAVBAR_HEIGHT) configuration:configuration];

    NSString *urlimage = @“你的h5网址”;

    NSURL*url = [NSURLURLWithString:urlimage];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [wevViewloadRequest:request];

    wevView.backgroundColor = [UIColor whiteColor];

    wevView.UIDelegate = self;

    wevView.navigationDelegate = self;

//监听方法,一定要与h5注册方法一致

    [userControlleraddScriptMessageHandler:self name:@"IntentSavePic"];

- (void)userContentController:(WKUserContentController*)userContentControllerdidReceiveScriptMessage:(WKScriptMessage*)message {

//因为之前监听了方法,如果不监听,这里是不会走的

    NSLog(@"+++++%@++++%@", message.body, message.name);

 if([message.nameisEqualToString:@"IntentCopy"]){

        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];

        pasteboard.string= message.body;

        [MBProgressHUDshowSuccess:@"已复制至剪贴板"];

    }elseif([message.nameisEqualToString:@"IntentSavePic"]){

        NSString*urlString =  message.body;

        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];

        UIImage*image = [UIImageimageWithData:data];// 取得图片

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

    }

}

- (void)image:(UIImage*)imagedidFinishSavingWithError:(NSError*)errorcontextInfo:(void*)contextInfo

{

        if(error !=NULL){

   [MBProgressHUD showSuccess:@"保存失败"];

        }else{

                     [MBProgressHUDshowSuccess:@"保存成功"];

                    }

}

相关文章

网友评论

    本文标题:iOS WKWebView H5界面调用OC方法 保存图片至相册

    本文链接:https://www.haomeiwen.com/subject/hdakoctx.html