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, ), ^(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();
}
});
});
}
上一篇:《redis设计与实现》读笔之redis过期与持久化


下一篇:JS对URL字符串进行编码/解码分析