javascript function access ios native features - javascript

This situation: Like PhoneGap, I want to define and call an inexistent JavaScript function, which need to access ios features. e.g.,
javascript code:
function onClickButton(){
toModule(true, true, "title1", 1);
}
I want to access iOS features through the function toModule. But How? Can you tell me?
PS: I know one solution JS->iOS is by using UIWebViewDelegate's
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
but I don't want that solution, just handle the JS function toModule(...)

From javascript(phonegap) you cant access ios native code directly instead you should use or develop a phonegap plugin that could establish this connection .
you can find more at Plugin Development Guide

This is very Simple
Step 1) Include cordova.js file in your project
Step2) Include cordova.js in your javascript file and in your javascript file add the following code
cordova.exec(
function successCallback() {
},
function errorHandler(err) {
},
'Login', 'callLogin', [param]);
}
here Login is the name of native class and callLogin is function in Login class, param is the array of parameters you want to send to native file
Step3) Goto config.xml and this
<feature name="Login">
<param name="ios-package" value="Login"/>
</feature>
Step4)
- (void)Login:(CDVInvokedUrlCommand*)command
{ // this is the native function, which is being called from javascript file, do your work here
}
Step5) If you want to send any data back to js file from native you need to write the below code.
NSString * jsCallBack = [NSString stringWithFormat:#"callJsFunction(parameters)];
[self.webView stringByEvaluatingJavaScriptFromString:jsCallBack];
callJsFunction() is the name of the js function which you want to call from native.(you can send string only)
Step6) To fetch value from native to js you need to write callJsFunction(parameters) in js file. write below function in js file
callJsFunction(parameters)
{
}
this is the complete process for calling native function from js and js from native class.

Related

Microsoft Visual Foxpro DLL call in Node or Java

I'm new to Visual Foxpro. I want to build a dynamic link library (dll) file using Visual Foxpro for calling the Visual Foxpro function in Node or Java to build rest API.
I tried it with Node and Java. I had an issue when I used the Foxpro dll file. So I created a C# dll, and got the same issue. So then I read a document which said to use > [DLLEXPORT] tag above the function which I want to call in another native language.
I built a 32-bit and 64-bit dll to use with my native language code. It was successful. My question is that I want to build both 32-bit and 64-bit dll files with Visual Foxpro to use with Node.js code.
This is my C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using net.r_eg.DllExport;
namespace FDLL
{
public class First
{
[DllExport]
public static String getData()
{
Console.Write("Call Function Successfully!");
return "HI Welcome";
}
}
[DllExport]
public static String getData1(String a)
{
Console.Write("Call Function Successfully!");
return "HI Welcome"+ a;
}
}
If I did not use [DllExport] tag, getData could not be invoked in my Node or java code.
This is my Node.js code:
const ffi = require("#saleae/ffi");
const libm = ffi.Library("./FDLL", {
getData: ["string", []],
getData1: ["string", ["string"]]
});
It works fine, but my Foxpro dll is not working.
This is my Visual Foxpro code:
This is the JavaScript code for accessing my Foxpro GetDrugsJSON() function
var libm1 = ffi.Library("./cw/comdemo", {
GetDrugsJSON: ["String", []],
});
console.log(libm1.GetDrugsJSON())
But I cannot invoke GetDrugsJSON() function with JavaScript code.
How do I fix this issue?
Long story short, you cannot build 32 and 64 bits DLL with VFP.
Also a DLL is a broad term (while it is short for Dynamic Link Library, there are different DLLs).
You are saying "in Node or Java to build rest API". For creating REST API you wouldn't want to use VFP. Use something else, be it C#, Go, ...
With other languages too, if you are accessing VFP data via VFPOLEDB then it needs to be 32 bits.

Call javascript method from Cordova Plugin's service

I am currently developing an App using Cordova and therefore have developed a Cordova Plugin, that runs a service and is being started from within that plugin:
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
switch(action){
case "start":
Intent startIntent = new Intent(context, BackgroundService.class);
startIntent.putExtra("action", "play");
context.startService(startIntent);
return true;
}
return false;
}
The code is shortened for readability. Now normally I would use callbacks to call javascript methods from within the plugin, but as I want to use a service for the functionality, how could I call a method (or maybe the callback) from there?
Thank you very much in advance :).
Okay so I did not find a way to this with vanilla cordova, but this Plugin provides the functionality I was looking for: https://github.com/bsorrentino/cordova-broadcaster
You have to set up a LocalBroadcastManager in your native Android Code and send an Intent with it. You then define a bundle containg the data you want to send, and put it as extra of your intent. Then you send the intent via the broadcast manager and receive it via javascript.
Sample Java:
startCallback = new Intent("callback");
Bundle b = new Bundle();
b.putString("callback", "start");
startCallback.putExtras(b);
LocalBroadcastManager.getInstance(applicationContext).sendBroadcastSync(startCallback);
Sample Javascript:
var callbackListener = function( e ) {
console.log("What kind of callback: " + e.callback);
};
window.broadcaster.addEventListener( "callback", callbackListener);
I hope this helps somebody with a similiar problem :).

How to pass a variable from javascript to objective C and Objective C to Javasctipt in ios

I am a iOS Developer, am new to javascript.
I wants to create a communication between Javascript to Objective C and Objective C to Javascript.
How to pass a variable from javascript to objective C and Objective C to Javasctipt in ios.
If any one have references please let us know about this?
I program JavaScript when using Parse CloudCode. In my case, I use CloudCode to call the Stripe API.
For example:
Objective-C
NSDictionary *parameters = #{
#"customerId": stripeCustomerId,
#"amount": #(100),
};
[PFCloud callFunctionInBackground:#"chargeCustomer" withParameters:parameters block:block];
JavaScript
Parse.Cloud.define("chargeCustomer", function(request, response) {
Stripe.Charges.create({
amount: request.params.amount, // in cents
currency: "usd",
customer: request.params.customerId,
},{
success: function (httpResponse) {
console.log(httpResponse);
response.success(httpResponse);
},
error: function (httpResponse) {
console.error(httpResponse.message);
response.error(httpResponse.message);
}
});
});
As you can see, to pass on the variable from objective-c to javascript in this case, you use request.params.
If you are targeting iOS8, you could consider to use WKWebView rather than UIWebView, which has considerably improved in this regard. Good starting points are the the WKWebView reference docs and this NSHipster article.
You can use native iOS objects to do this.
From Obj-C to JS
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
It injects or calls pre-existing method/object in the page loaded in the UIWebview. It returns the value that JS return to you
UIWebView Class Reference
From JS to Obj-C
Implementing UIWebView protocol you can handle the request before it will start:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest (NSURLRequest *)request navigationType (UIWebViewNavigationType)navigationType
So, from JS you have to call a URL with a custom schema http such as test://. Then you will parse the request in the delegate method I wrote before.

Pushwoosh phonegap plugin, retrieving hwid on ios

I'm using pushwoosh to send push notifications to my ios mobile app. I want to allow users to disable notifications from within the app. The problem I'm having is that the pushwoosh api uses a different device id for ios than it does for android. The device id is created by the plugin using native code. It uses the hardware mac address and applies the md5 algorithm to create a "unique" id that phonegap is calling "hwid"(hardware id). I've found the native, objective c class that does this but I don't know how to access the variable, "hwid", from Javascript.
I've read through the phonegap documentation and have created a plugin that allows me to access native ios classes. My problem is that I don't know objective c and therefore cannot figure out how to return the variable to the callback.
The pushwoosh api requires the device id in order to unregister a device as you can see here:
{
"request":{
"application":"APPLICATION_CODE",
"hwid": "hardware device id"
}
}
I have seen this post and it is not helpful for what I'm trying to accomplish. However, it does show the native code that creates the unique id.
I also found this class that prints the hwid to the console. If I could find a way to access the "hwid" below from my js code I would be all set.
#import "PWRequest.h"
#implementation PWRequest
#synthesize appId, hwid;
- (NSString *) methodName {
return #"";
}
//Please note that all values will be processed as strings
- (NSDictionary *) requestDictionary {
return nil;
}
- (NSMutableDictionary *) baseDictionary {
NSMutableDictionary *dict = [NSMutableDictionary new];
[dict setObject:appId forKey:#"application"];
[dict setObject:hwid forKey:#"hwid"];
NSLog(#"hwid: %#", hwid);
return [dict autorelease];
}
- (void) parseResponse: (NSDictionary *) response {
}
- (void) dealloc {
self.appId = nil;
self.hwid = nil;
[super dealloc];
}
#end
Can someone point me in the right direction? Thanks.
We have just added unregisterDevice method for iOS Phonegap Javascript.
PushNotification.prototype.unregisterDevice = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "unregisterDevice", []);
};
It used to work only for Android, now it is available on iOS as well.
For Phonegap 3.0 please see the newest Pushwoosh plugin repo:
https://github.com/shaders/pushwoosh-phonegap-3.0-plugin
For older Phonegap versions <= 2.9 please see legacy Pushwoosh Phonegap plugin:
https://github.com/shaders/phonegap-cordova-push-notifications/tree/master/iOS
I hope it helps!
I found a work-around for anyone who needs this. Just open up the class "PWRequest.m" in xcode. Add the code below just under "[dict setObject:hwid forKey:#"hwid"];" in the NSMutableDictionary method.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"hwidfile2.txt"];
NSLog(#"From Echo Class File Path: %#", filePath);
NSString *str = hwid;
This will save a text file to your local app directory in which you can access from your Javascript code. For example, you can use this JS code to access and print the hwid to the console. Just call the 'readPwfile(filename)' function, passing in the name of your file as the function argument.
function readPWFile(fileName){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
fileSystem.root.getFile(fileName, null, gotReadFileEntry, fail);
});
function gotReadFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
//readDataUrl(file);
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log('Reading file... hwig Result: '+evt.target.result);
};
reader.readAsText(file);
}
}

How to link to Windows 8 Phone Store App review for my app?

I don't want to open the browser but the actual store in my Windows 8 phone.
I am developing an app using PhoneGap and so I want to do this with Javascript.
I haven't submitted my app so I don't yet have a package name. How do I test this without an actual package name?
Also, I can't seem to be able to use:
Windows.System.Launcher.LaunchUriAsync(new Uri(appStoreURL));
I get:
Error:["'Windows' is undefined file:x-wmapp0:www\/js\/......
Any ideas?
SOLUTION:
Using Benoit's answer and some other stuff I found I managed to link straight to the review section by adding the following Plugin to my cordovalib:
LaunchReview.cs
using WPCordovaClassLib.Cordova.Commands;
using Microsoft.Phone.Tasks;
namespace Cordova.Extension.Commands
{
public class LaunchReview : BaseCommand
{
public void launchReview(string options)
{
// Use the Marketplace review task to launch the Store or Marketplace and then display the review page for the current app.
MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
marketplaceReviewTask.Show();
}
}
}
Note sure what value you are using for appurl but here is something which should work:
Windows.System.Launcher.LaunchUriAsync(new Uri("zune:reviewapp"));
or you can use:
MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
marketplaceReviewTask.Show();
To call it from javascript just create a plugin:
namespace Cordova.Extension.Commands
{
public class LaunchReview: BaseCommand
{
public void launchReview(string options)
{
// all JS callable plugin methods MUST have this signature!
// public, returning void, 1 argument that is a string
MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
marketplaceReviewTask.Show();
}
}
}
that you can use it like this from javascript:
cordova.exec(win, fail, "LaunchReview", "launchReview", [""]);
Here is the link to the plugin dev guide for windows phone
If you want to use window.open then you will need to modify the PhoneGap source code to use LAunchUri because currently it's just using WebBrowserTask instead of LaunchUri. The function to modify is Plugin/InAppBrowser.cs>ShowSystemBrowser
I used InAppBrowser cordova plugin.
cordova plugin add org.apache.cordova.inappbrowser
To open wp8 store i call from javascript:
window.open(UrlToMyApp, '_blank', 'location=yes');

Categories