简体   繁体   English

如何在 iPad 上使用 JavaScript/Obj-C 将图像保存到照片库?

[英]How to save image to Photo gallery using JavaScript/Obj-C on iPad?

I'm currently developing a small, JavaScript based drawing application on iPad.我目前正在 iPad 上开发一个基于 JavaScript 的小型绘图应用程序。 I've simply wrapped it inside UIWebView like this .我只是像这样将它包裹在 UIWebView 中。 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.现在问题是我不知道如何从应用程序中保存图像,以便将其存储在 iPad 照片上。

Is there some simple way to bridge JavaScript code with Objective-C one?有没有一些简单的方法可以将 JavaScript 代码与 Objective-C 代码连接起来? 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.我想我可以从 JS 端传递一个包含 PNG 图像数据的字符串,然后使用 Objective-C 以某种方式将其保存到照片库中。

Yes, there is a way to bridge javascript from a UIWebView to Obj-C code.是的,有一种方法可以将 javascript 从 UIWebView 桥接到 Obj-C 代码。

Set your UIWebView delegate, and in your delegate paste in the following method设置您的 UIWebView 委托,并在您的委托中粘贴以下方法

//
// 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.然后你可以编写处理请求的 Obj-C 方法。 For example.例如。 In your webview you might have a button that has a link tag like在您的 webview 中,您可能有一个带有链接标签的按钮,例如

<a href="file://myGreatApp.com/saveImage">Click Me to Save Image </a>

The scheme is "file" the fragment is "saveImage".方案是“文件”,片段是“saveImage”。 You can now write an Obj-C method您现在可以编写一个 Obj-C 方法

-(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.编辑:如果你想在你的方法中传递字符串参数,只需 append 使用 javascript 将它们传递给你的片段 url。 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 '*'.然后在您的 Obj-C 代码中,在字符“*”上拆分片段。 Use the first half as your selector and the second half as the parameter.使用前半部分作为选择器,后半部分作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM