I'm currently developing a small, JavaScript based drawing application on iPad. I've simply wrapped it inside UIWebView like this . Now the thing is that I can't figure out how to save an image from the app so that it's stored on iPad photos.
Is there some simple way to bridge JavaScript code with Objective-C one? I guess I could pass a string containing PNG image data from the JS side and then use Objective-C to save it to the photo gallery somehow.
Yes, there is a way to bridge javascript from a UIWebView to Obj-C code.
Set your UIWebView delegate, and in your delegate paste in the following method
//
// Map links starting with file://
// ending with #action
// with the action of the controller if it exists.
//
// Open other links in Safari.
- (BOOL)webView: (UIWebView*)webView shouldStartLoadWithRequest: (NSURLRequest*)request navigationType: (UIWebViewNavigationType)navigationType {
NSString *fragment, *scheme;
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
[webView stopLoading];
fragment = [[request URL] fragment];
scheme = [[request URL] scheme];
if ([scheme isEqualToString: @"file"] && [self respondsToSelector: NSSelectorFromString(fragment)]) {
[self performSelector: NSSelectorFromString(fragment)];
return NO;
}
[[UIApplication sharedApplication] openURL: [request URL]];
}
return YES;
}
Then you can write Obj-C methods that'll handle the request. For example. In your webview you might have a button that has a link tag like
<a href="file://myGreatApp.com/saveImage">Click Me to Save Image </a>
The scheme is "file" the fragment is "saveImage". You can now write an Obj-C method
-(void)saveImage;
That will be called every time a user clicks on the link.
Edit: If you want to pass string parameters in your method, simply append them to your fragment url using javascript. So instead you might have
<a href="file://myGreatApp.com/saveImage*asdgo8asdgl35lkjasgd807ll12">Click Me to Save Image </a>
Then in your Obj-C code, split the fragment on the char '*'. Use the first half as your selector and the second half as the parameter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.