Use JavaScript to invoke native APIs in iOS WebView

Source: Internet
Author: User

1. First include the relevant code in JavaScript

$ ('. Content. Savecode '). On (' Touchstart ',function() {//Touchstart        if(temp = = 0) {jump (); }        if(Temp = = 1) {android.savepic (IMAGE.SRC);}    }); functionJump () {//IOS        varTouchstart =true; Window.location= "/touchstart";//Change URL Note: To use the "/" delimiter    }    functionPoststr () {//IOS        returnimage.src; }

2. iOS save picture to local code

//when you have finished loading the page, take it to ImageUrl
- (void) Webviewdidfinishload: (UIWebView *) webview{_urlstring= [_mywebview stringbyevaluatingjavascriptfromstring:@"poststr ();"]; NSLog (@"%@", _urlstring);} Call Order-Shouldstart->finishload-> Callback block function
-(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:didfinishsavingwitherro R:contextinfo:), nil); }, ^(void) {NSLog (@"error!"); }); return false; } return true;}voidUiimagefromurl (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 (); } }); });}

Use JavaScript to invoke native APIs in iOS WebView

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.