Compress image plugin for ios in phonegap - javascript

I am new to ios and building compress image plugin in ios for phonegap.I am not getting how to call the compress image method in my javascript. My code is, Plugin.h file
- (void) cordovaCompressimg:(CDVInvokedUrlCommand *)command;
Plugin.m file
- (void) cordovaCompressimg:(CDVInvokedUrlCommand *)command
{
UIImage *sourceImage ;
NSString *compimg =[self UIImageToBaseSixtyFour];
CDVPluginResult *pluginResult = [ CDVPluginResult
resultWithStatus : CDVCommandStatus_OK
NSData : compimg
];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
-(NSData *)UIImageToBaseSixtyFour
{
UIImage *sourceImage ;
NSData *imageData = UIImageJPEGRepresentation(sourceImage, 1.0);
NSString *base64 = [NSString stringWithFormat:#"%#",[UIImageJPEGRepresentation(sourceImage, 0.95) base64EncodedString]];
return base64;
}
plugin.js file
window.showimg = function(cimg, callback) {
cordova.exec(callback, function(err) {
callback('Nothing to echo.');
}, "PhonegapPlugin", "cordovaGetCurrentDate", [cimg]);
};
my calling function in index.html is,
function showCompressimg() {
window.showimg("", function(echoValue)
{
alert(echoValue);
});
}
The plugin is getting called but with empty image.The out put comes as null.The source image is not getting passed.Can anybody help me please,
Thanks in advance

You are passing the source image correctly, but you are not retrieving the image passed in your argument in objective-c code. Whenever you pass any argument via plugin Javascript, those arguments are stored in CDVInvokedUrlCommand instance command. So you can modify your code like this -
- (void) cordovaCompressimg:(CDVInvokedUrlCommand *)command
{
//Arguments are passed in an Array. Source Image is present at Index 0
UIImage *sourceImage = [command argumentAtIndex:0];
NSString *compimg =[self UIImageToBaseSixtyFour:sourceImage];
CDVPluginResult *pluginResult = [ CDVPluginResult
resultWithStatus : CDVCommandStatus_OK
NSData : compimg
];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
-(NSData *)UIImageToBaseSixtyFour:(UIImage *)img
{
//UIImage *sourceImage ;
NSData *imageData = UIImageJPEGRepresentation(img, 1.0);
NSString *base64 = [NSString stringWithFormat:#"%#",[UIImageJPEGRepresentation(img, 0.95) base64EncodedString]];
return base64;
}

Related

How to close WKWebView via javascript on the site?

I have a finished application. I can not implement the closure of VKWebView from registration at the end of registration. Since I have not encountered this in the lens - p.
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
webView.navigationDelegate = self;
webView.customUserAgent = "Cron";
[self.view addSubview:webView];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://myUrl"]];
[webView loadRequest:request];
in order to interact with the WKWebView, you can use the javascript functions for them.
After the WKWebView has finished loading (via delegate for example), yo can use the evaluateJavascript functions, to trigger any event in the web or in your iOS code.
For example:
[self.webview evaluateJavaScript:#"var foo = 1; foo + 1;" completionHandler:^(id result, NSError *error) {
if (error == nil)
{
if (result != nil)
{
NSInteger integerResult = [result integerValue]; // 2
NSLog(#"result: %d", integerResult);
}
}
else
{
NSLog(#"evaluateJavaScript error : %#", error.localizedDescription);
}
}];
The javascript function is:
var foo = 1; foo + 1;
There you can set any javascript function from objective-c side, or call any function in the web side.
For example, if you have a javascript function in your web site called:
func closeWeb()
You have to set the function like this:
[self.webview evaluateJavaScript:#"closeWeb();" completionHandler:^(id result, NSError *error) {
if (error == nil)
// Code for success
} else {
NSLog(#"evaluateJavaScript error : %#", error.localizedDescription);
}
}];

how to pass data from javascript to IOS Objective-c in webview?

I have a web app which i am using as Web-view app for android and IOS app.I need to pass user data to the web-view app which i achieved for android but i have no knowledge on how to do it for IOS web-view.
I have my IOS code in x-code which is in objective-c and i need to send data from frontend javascript to Objective-c, which can access it.
below is my javascript code
var myAppName = 'myfakeappname';
var myActionType = 'myJavascriptActionType';
var myActionParameters = {}; // put extra info into a dict if you need it
// (separating the actionType from parameters makes it easier to parse in ObjC.)
var jsonString = (JSON.stringify(myActionParameters));
var escapedJsonParameters = escape(jsonString);
var url = myAppName + '://' + myActionType + "#" + escapedJsonParameters;
document.location.href = url;
below is my code from Viewcontroller.m
#import "ViewController.h"
#import <WebKit/WebKit.h>
#interface ViewController ()<WKNavigationDelegate>
#property (weak, nonatomic) IBOutlet WKWebView *vwWeb;
#property (weak, nonatomic) IBOutlet UIView *vwLoading;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.vwWeb.navigationDelegate = self;
NSURL *nsurl=[NSURL URLWithString:#"http://localhost:3000"];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[self.vwWeb loadRequest:nsrequest];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
self.vwLoading.hidden = YES;
}
//below is the code i copy pasted from various resourses i found from forums
- (BOOL)webView:( WKWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
// these need to match the values defined in your JavaScript
NSString *myAppScheme = #"myfakeappname";
NSString *myActionType = #"myJavascriptActionType";
// ignore legit webview requests so they load normally
if (![request.URL.scheme isEqualToString:myAppScheme]) {
return YES;
}
// get the action from the path
NSString *actionType = request.URL.host;
// deserialize the request JSON
NSString *jsonDictString = [request.URL.fragment stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSLog(#"Hello, World!");
// look at the actionType and do whatever you want here
if ([actionType isEqualToString:myActionType]) {
NSLog(#"Missing function name");
// do something in response to your javascript action
// if you used an action parameters dict, deserialize and inspect it here
}
// make sure to return NO so that your webview doesn't try to load your made-up URL
return NO;
}
#end
Any help or suggestion will be greatly appreciated.
If your parameters is in the url, extract it by this property navigationAction.request.url in this function to get the params:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: #escaping (WKNavigationActionPolicy) -> Void)
Exactly like you started:
In JavaScript the buttons/links that need to trigger something on iOS app should do: window.location="myappname://func1";
Javascript should also have a accessible method (ie should be accessible from browser console for example) myobject.jsfunc()
On iOS WebView you intercept requests with myappname:// URL, something like:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *URL = [request URL];
NSString *requestStr = [[request URL] absoluteString]; //Get the URL
//NSLog(#"Native method call '%#'", requestStr);
if ([requestStr hasPrefix:#"openpanzer"]) {
//The [URL host] is the next part of the link so we can use that like a selector
NSString *selectorName = [URL host];
id data = nil;
NSMutableArray *parameters = [NSMutableArray array];
if ( ![[URL path] isEqualToString:#""] )
{
selectorName = [NSString stringWithFormat:#"%#:", selectorName];
parameters = [NSMutableArray arrayWithArray: [[URL path] componentsSeparatedByString:#"/"] ];
[parameters removeObjectAtIndex:0]; //first object is just a slash "/"
if ( [parameters count] == 0 ) {
data = nil;
NSLog(#"NIL parameter call");
}
else if ( [parameters count] == 1 ) {
data = [parameters objectAtIndex:0];
NSLog(#"Single parameter call %#", data);
}
else {
data = parameters;
}
}
SEL method = NSSelectorFromString( selectorName );
if ([nativeGlue respondsToSelector:method]) {
if (data == nil)
[nativeGlue performSelector:method];
else
[nativeGlue performSelector:method withObject:data];
}
else {
NSLog(#"Can't find native method '%#' with param '%#'", selectorName, data);
}
return NO;
}
return YES;
}
On iOS (WebViewDelegate or AppDelegate) define your func1 ie: - (void) func1
If you need to send back results to your javascript app use:
[webView callJSFunction: jsFunc];

JavaScriptCore and Objective C problems

I'm trying to use the following javascript library with JavasScriptCode in iOS: javascript library
I'm reading it with the following code and everything looks great!
self.jsContext = [[JSContext alloc] init];
NSURL *scriptURL = [NSURL URLWithString:#"https://cdn.rawgit.com/Ambisafe/client-javascript/master/dist/ambisafe.js"];
NSError *error = nil;
NSString *script = [NSString stringWithContentsOfURL:scriptURL encoding:NSUTF8StringEncoding error:&error];
[self.jsContext evaluateScript:script];
When I run the following code, I have the expected results:
NSString *script = [NSString stringWithFormat:#"Ambisafe.generateRandomValue"];
NSString *value = [[self.jsContext evaluateScript:script] toString];
Results:
function (length) {
var randomBytes;
if (!length) {
length = 256 / 16;
}
randomBytes = crypto.randomBytes(Math.ceil(length));
return randomBytes.toString('hex');
}
When I try to run the indicated function, I have an "undefined" result:
NSString *script = [NSString stringWithFormat:#"Ambisafe.generateRandomValue(30)"];
NSString *value = [[self.jsContext evaluateScript:script] toString];
I executed the following code, and I have an "undefined" result too:
NSString *script = [NSString stringWithFormat:#"crypto"];
NSString *value = [[self.jsContext evaluateScript:script] toString];
If I test the indicated javascript library on a browser, it works fine!
Please check the Fiddle link.
Any idea?
I found the origin of the problem.
The indicated library uses the "window.crypto.getRandomValues" and it doesn't work in older browsers.
https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues

Phonegap handleOpenURL not called on app launch (iOS)

Getting alert message when app is open in background.When I close the app from background when I launch the app it don't give me alert message. handleOpenURL not able to invoke in JavaScript when app is first time launch. Following are code
didFinishLaunchingWithOptions Code
NSURL* url = [launchOptions objectForKey:UIApplicationLaunchOptionsURLKey];
NSString* invokeString = nil;
if (url) {
invokeString = [url absoluteString];
NSLog(#"iPaperReeder launchOptions = %#", url);
}
self.viewController.invokeString = invokeString;
AppDelgate.m
if (!url) { return NO; }
NSString* jsString = [NSString stringWithFormat:#"window.setTimeout(function(){ handleOpenURL(\"%#\"); }, 1)", url];
[self.viewController.webView stringByEvaluatingJavaScriptFromString:jsString];
// all plugins will get the notification, and their handlers will be called
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];
return YES;
It should output to this javascript function:
function handleOpenURL(url) {
alert('invoke: ' + url);
}
Please help me.
I think you are not doing right, Please follow my code as below:
You can easily sort out this problem.
In "CDVHandleOpenURL.m" file you need to change code as below :
NSString* jsString = [NSString stringWithFormat:#"document.addEventListener('deviceready',function(){if (typeof handleOpenURL === 'function') { handleOpenURL(\"%#\");}});", url];
To
NSString* jsString = [NSString stringWithFormat:#"if (typeof handleOpenURL === 'function') { handleOpenURL(\"%#\");} else { window._savedOpenURL = \"%#\"; }", url, url];
this will work perfectly.
Best of luck

Objective-C Dropbox SDK File Download - Listen for Download Complete

I am making a call to Objective C from a PhoneGap application to perform functions with Dropbox.
The problem I am having is that my callback to JavaScript is firing before a file is downloaded from Dropbox to the phone's local filesystem.
Here is my Objective C method that begins the file download from Dropbox -
- (void) restore:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSString* javaScript = nil;
NSLog(#"Dropbox restore method is executing");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSString *localPath = [documentsDirectory stringByAppendingPathComponent:#"PocketHealth-backup.bk"];
NSString *dropBoxFile = #"/PocketHealth-backup.bk";
[[self restClient] loadFile:dropBoxFile intoPath:localPath];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
javaScript = [pluginResult toSuccessCallbackString:command.callbackId];
[self writeJavascript:javaScript];
}
There is a method in Objective C that executes when the Dropbox file has been downloaded to the phone. I do get the NSLog that this method outputs after the Dropbox file download is complete. The problem is that I need to know when this event happens before I can return my JavaScript callback.
Here is the method that executes when the Dropbox file download is complete -
- (void) restClient:(DBRestClient*)client loadedFile:(NSString*)localPath
{
NSLog(#"File loaded into path: %#", localPath);
}
How can I wait until the Dropbox file download is complete before returning the JavaScript callback that is in the restore method?
Instead of writing the JavaScript into a local variable inside your restore method, add it as an iVar to your class, remove the call to writeJavascript: in your restore method and call writeJavascript from restClient:loadedFile:. Then it should get called when the download finished instead of when the actual download is started.
- (void) restore:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSLog(#"Dropbox restore method is executing");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSString *localPath = [documentsDirectory stringByAppendingPathComponent:#"PocketHealth-backup.bk"];
NSString *dropBoxFile = #"/PocketHealth-backup.bk";
[[self restClient] loadFile:dropBoxFile intoPath:localPath];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
self.javaScript = [pluginResult toSuccessCallbackString:command.callbackId];
}
- (void) restClient:(DBRestClient*)client loadedFile:(NSString*)localPath
{
NSLog(#"File loaded into path: %#", localPath);
[self writeJavascript:javaScript];
}

Categories