iOS的WebView中使用javascript调用原生的api

1. 首先在javascript中加入相关代码

$(‘.content .saveCode‘).on(‘touchstart‘, function () {//touchstart
        if (temp == 0) {
            jump();
        }
        if (temp == 1) { android.savePic(image.src); }
        
    });

    function jump() {//IOS
        var touchstart = true;
        window.location = "/touchstart";     //改变URL  注意:要使用"/"分隔符 
    }

    function postStr() {//IOS
        return image.src;
    }

 

2. iOS保存图片到本地代码

// 当加载完网页取到imageurl
- (void)webViewDidFinishLoad:(UIWebView *)webView { _urlString = [_myWebView stringByEvaluatingJavaScriptFromString:@"postStr();"]; NSLog(@"%@",_urlString); } // 调用次序 - shouldStart->FinishLoad->回调block函数
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if ([request.mainDocumentURL.relativePath isEqualToString:@"/touchstart"]) { UIImageFromURL( [NSURL URLWithString:_urlString], ^( UIImage * image ) { UIImageWriteToSavedPhotosAlbum( image, self, @selector( onSaveComplete:didFinishSavingWithError:contextInfo: ), nil ); }, ^(void){ NSLog(@"error!"); }); return false; } return true; } void UIImageFromURL( NSURL * URL, void (^imageBlock)(UIImage * image), void (^errorBlock)(void) ) { dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void) { NSData * data = [[NSData alloc] initWithContentsOfURL:URL]; UIImage * image = [[UIImage alloc] initWithData:data]; dispatch_async( dispatch_get_main_queue(), ^(void){ if( image != nil ) { imageBlock( image ); } else { errorBlock(); } }); }); }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。