Importing JavaScript file into Swift file - javascript

I am trying to execute a JavaScript SDK from within a Swift application. I am unable to find the file however. I added the file to the project using cmd + click project -> Add files to "projectName" -> Add file and move into projectName/ folder.
I am still unable to get the file and run it inside a JSContext.
Where am I going wrong?
Here is my code (isOK is just used for a test case):
import Foundation
import JavaScriptCore
public class Wrapper {
public var isOK: Bool
var jsContext: JSContext
init (pathToSdk: String) {
let virtualMachine = JSVirtualMachine()
self.jsContext = JSContext(virtualMachine: virtualMachine)
if let sdkBundle = Bundle.main.path(forResource: pathToSdk, ofType: "js") {
let bundleString = try! String(contentsOfFile: sdkBundle)
self.jsContext.evaluateScript(bundleString)
print("Successfully initialised JavaScript context")
self.isOK = true
} else {
print("Unable to fetch SDK bundle at path: \(pathToSdk)")
self.isOK = false
}
}
}
I call it in my test:
func testIsOK() {
let wrapper = Wrapper(pathToSdk: "sdk").isOK
XCTAssertEqual(wrapper, true)
}
And my folder structure:
Thanks and sorry if this is a silly question, I'm brand new to Swift.

Related

Get Visual Studio Code to give intellisense for custom Javascript imports

I am writing automated testing scripts using TestComplete. TestComplete mostly supports Ecmascript 2015, but it has a few quirks that are causing intellisense to not work as I would expect.
Here is two examples of code files:
File: UsefulStuffFileName.js
class UsefulStuff {
constructor(initValue) {
this.initValue = initValue;
}
get someValue(){
return this.initValue + " someValue";
}
doStuff(input) {
return input + " stuff done";
}
}
module.exports.UsefullStuff = UsefullStuff;
File: WorkingHere.js
var useful = require('UsefulStuffFileName');
class WorkingHere {
constructor() {
this.usefullStuff = new useful.UsefulStuff("Hello");
}
doCoolStuff() {
// I want intellisense options when I type the period after this.usefulStuff
// The options would be someValue, doStuff() and initValue.
// |
// |
// V
let myVariable = this.usefullStuff.someValue;
}
}
The quirks, as I see them are:
The export is done via this style: module.exports.UsefullStuff = UsefullStuff;. (This makes it work with TestComplete.)
The "import" assigns to a variable (var useful = require('UsefulStuffFileName');)
The "new"ing of the object uses the variable to access the class (new useful.UsefulStuff("Hello");).
Is there anyway to configure Visual Studio Code to understand how these files are related and give me intellisense?
Note: If I try the more standard import {UsefulStuff} from './UsefulStuffFileName'; I get an error saying "Unexpected token import" from TestComplete.
This can be done via these steps.
Change the import to look like this:
var { UsefulStuff } = require('UsefulStuff');
Change the instantiation of the class to look like this:
this.usefulStuff = new UsefulStuff("Hello");
Add a file called jsconfig.json and put this in it:
.
{
"compilerOptions": {
"baseUrl": "."
}
}

Vibe.d - Can not generate JS script for rest api

I'm trying to generate JS for my simple REST API like eg described here: doc. My example code:
import vibe.d;
import wbapi;
import std.array : appender;
import vibe.core.file;
void main()
{
// generate JS for access
auto test = appender!string;
auto settingsJS = new RestInterfaceSettings;
settingsJS.baseURL = URL("http://localhost/api/integration/");
generateRestJSClient!IfWhiteBlowerAPI(test, settingsJS);
}
and interface:
#path("/api/integration")
interface IfWhiteBlowerAPI
{
Json get();
string postDeaf(Json obj);
}
Everything is compiling without any problem but i can't find generated JS anywhere. Am i looking in wrong place - main tree of app project?
I get help on vibed IRC channel. There is appender which is "handling" generated JS data. After we generate it we need to save it to file manually, below working example:
import vibe.d;
import std.stdio;
import std.array : appender;
import vibe.core.file;
#path("/api/integration")
interface IfWhiteBlowerAPI
{
Json get();
string postDeaf(Json obj);
}
void main()
{
// generate JS for access
auto test = appender!string;
auto settingsJS = new RestInterfaceSettings;
settingsJS.baseURL = URL("http://localhost/api/integration/");
generateRestJSClient!IfWhiteBlowerAPI(test, settingsJS);
auto f = File("test.js", "w");
f.write(test.data);
f.close();
}

NodeJs require error

I have a nodejs package and i have a linkedList code. I want to include my LinkedList code in my NodeJs js folder but I can't do it. What is the my fault ?
I want to use it like this
This is my code in my NodeJs folder.(app.js)
var KullaniciJS=require('KullaniciLibrary.js');
This is my required folder codes.(KullaniciLibrary.js)
function Kullanici(KullaniciAdi)
{
this.KullaniciAdi=KullaniciAdi;
this.Sonraki=null;
}
function KullaniciListe()
{
this.Bas=null;
this.Uzunluk=0;
}
KullaniciListe.prototype.Ekle=function(EklenecekKullaniciAdi)
{
var Bas=this.Bas;
if (!Bas) {
this.Bas = EklenecekKullaniciAdi;
this.Uzunluk++;
return EklenecekKullaniciAdi;
}
while (Bas.Sonraki!==null) {
Bas = Bas.Sonraki;
}
Bas.Sonraki = EklenecekKullaniciAdi;
this.Uzunluk++;
return EklenecekKullaniciAdi;
};
First you have to declare inside of your KullaniciLibrary.js file, what you want to export. you do this by adding following line at the end of the file:
module.exports = YOUREXPORT;
YOUREXPORT will probably just be the methodname (or some object).
After that, you wanna import it like this:
var KullaniciJS = require('./KullaniciLibrary');
Note that you have to prefix the name with ./ and you don't need to define the file-ending.
If you don't prefix the module with ./, node will search for the module in the node_modules folder, instead of the current directory
In nodejs to require a function from another file you have to export then function.
To export the function use:
module.export='your function name';
and to require the function use:
const variable=require(./filename)
for more understanding use this link:
https://nodejs.org/api/modules.html

Swift: Print Html title of WebView using Swift And JavaScriptCore

I have this .html data in my Xcode project:
I'm trying to read the title value using both of these lines:
document.title
document.getElementsByTagName(\"title\")[0].innerHTML;
but it only prints:
result is: undefined
import UIKit
import JavaScriptCore
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let myWebView:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
let localfilePath = NSBundle.mainBundle().URLForResource("home", withExtension: "html");
let myRequest = NSURLRequest(URL: localfilePath!);
myWebView.loadRequest(myRequest);
//let jsSource = "var testFunct = function(message) { return document.title;}"
let jsSource = "var testFunct = function(message) { return document.getElementsByTagName(\"title\")[0].innerHTML;}"
let context = JSContext()
context.evaluateScript(jsSource)
let testFunction = context.objectForKeyedSubscript("testFunct")
let result = testFunction.callWithArguments(["the message"])
print("result is: \(result)")
self.view.addSubview(myWebView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Don't use UIWebView for new code targeting iOS 8 and above, use WKWebView instead. Apple has this to say on UIWebView Documentation:
In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView. Additionally, consider setting the WKPreferences property javaScriptEnabled to NO if you render files that are not supposed to run JavaScript.
And here's how you can evaluate Javascript with WKWebView:
self.webView.evaluateJavaScript("document.title") { result, error in
print(result!)
}

WinRT - Starting/Registering IBackgroundTask in universal application

I would like to start my IBackgroundTask when my application starts up.
I have added my task to the .appxmanifest.xml file, and my extensions tag now looks like this
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="CordovaApp.Library.UploadTask">
<BackgroundTasks>
<Task Type="systemEvent" />
<Task Type="timer" />
</BackgroundTasks>
</Extension>
</Extensions>
My IBackgroundTask class is called UploadTask and is held in another project which has the outtype set to Windows Runtime Component.
Here is a cut down version of the code, so you can see the namespace etc
namespace CordovaApp.Library
{
public sealed class UploadTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
var connectionProfile = NetworkInformation.GetInternetConnectionProfile();
// connectionProfile can be null (e.g. airplane mode)
if (connectionProfile != null && connectionProfile.IsWlanConnectionProfile)
{
// custom code here
}
}
}
}
I have added a reference to this project to my universal runtime component project.
Everything builds fine.
Now to start the application, i guess i have to use WinJs, so i have the following code.
var uploadTaskName = 'UploadTask';
var tasks = Windows.ApplicationModel.Background.BackgroundTaskRegistration.allTasks;
var uploadTaskFound = false;
for (var i = 0; i < tasks.length; i++) {
if (tasks[i].Value.name == uploadTaskName) {
successCallback();
return;
}
}
Windows.ApplicationModel.Background.BackgroundExecutionManager.requestAccessAsync().then(function() {
var builder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();
builder.name = "Upload Task";
builder.taskEntryPoint = "CordovaApp.Library.UploadTask";
builder.setTrigger(new Windows.ApplicationModel.Background.TimeTrigger(15, false));
return builder.register();
}).done(function () {
successCallback();
}, function(err) {
errorCallback(err);
});
Now the requestAccessAsync method always throws an exception of
0x80004005 - JavaScript runtime error: Unspecified error
WinRT information: The application is not lock-screen capable.
Have a registered everything correctly? I am running this via Visual Studio 2013 on a laptop.
Seems that because the app was already installed, the permission was not given.
By uninstalling the application, and re-running it, i was then prompted to allow/disallow the background service to run. Checked allow, and now seems to work

Categories

Resources