Changing the splash screen at runtime

If you save an app to the home screen on an iOS device, you can display a nice splash screen when it launches. But what if the user switches to a different app, then returns to yours? It will have quit and needs to launch again.

You can save the current state to localStorage and write some code to go right back to where you were: but the splash screen will show again. You can suppress it by adding these lines to your restart code:

Dim headerChildren=document.getElementsByTagName("head")[0].children
Dim i=0
Do While i<UBound(headerChildren) And headerChildren[i].rel<>"apple-touch-startup-image"
  i=i+1
Loop
document.getElementsByTagName("head")[0].removeChild(headerChildren[i])

This code finds the splash screen in the header of the page and removes it.

Tip: Embedding NS Basic Apps in web pages

You might be wondering how I managed to embed an NS Basic app in the following post about jQuery Mobile.

Easy – here is the HTML:

<iframe src="http://www.nsbasic.com/KitchenSink" width=320 height=480>
</iframe>

You can now run the app as normal. Great way to do demos!

jQuery Mobile and App Studio

NS Basic/App Studio 2.0 introduces support for jQuery Mobile. This will let you develop more powerful and better looking apps. Here’s an actual App Studio program which shows off all the jQuery Mobile controls.


(go ahead – click on it!)

History
First, a bit of history. jQuery is a library of useful JavaScript functions that is being developed by John Resig and the jQuery Team. Backers of the the jQuery Project include Adobe, Mozilla, BlackBerry, Nokia, Microsoft and many more. Approximately 52% of the top web sites use jQuery.

Development of jQuery Mobile started in 2010: the first release was in November, 2011. This went far beyond what jQuery itself did: it actually contains a full set of visual elements, optimized for mobile devices. It was an instant success: jQuery Mobile is very widely used for Mobile Application development.

When we started development of NS Basic/App Studio, jQuery Mobile did not exist. We realized that having a library of controls was an essential part of the product. The best one at the time, and still a very good one today, was iWebKit. Distributed under the Apache license, we included it in our product. It is now called “Classic” in App Studio.

We started on the integration of jQuery Mobile some time before its actual release. As we worked with it, we realized that it added some very nice features to App Studio, so we accelerated development. Quite a bit of work was needed to make the IDE work well with both Classic and jQuery Mobile. The good news is that it came out great.

Features
There are a number of nice things to the jQuery Mobile controls.

  • Themes – you can customize the look and feel of the controls.
  • Grouped controls – Combine several similar controls into one large one.
  • Icons – a nice built in set of icons that can be used on many controls.
  • Additional Controls: FooterBar, FlipToggle, NavBar
  • More powerful controls: A number of controls have additional features.

Compatibility
Since Classic and jQuery Mobile have conflicting CSS, you cannot use both in the same project. When you create a project, you select which framework you are using. Only controls which apply to that framework will show in the ToolBox.

Some controls have two versions as a result: one for Classic and one for jQuery Mobile. These include Button, CheckBox, RadioButton, TextArea, TextBox and more.

Other controls work fine with both frameworks: Grid, Image, PictureBox, Audio, Video, HTMLview and more.

Conversion
The best way to convert a project is to open a new App Studio project with jQuery Mobile set as the framework. Create your forms again using the jQuery Mobile controls, giving them the same names as you had in Classic. You will need to reposition and resize many of the controls: the jQuery versions are often larger than the Classic version. Once the forms are done, copy and paste the code. Most of the code will come over without changes.

Ajax made Simple Part 3: Data from another site

One of the basic security features of the modern web is the Same Origin Policy. It states that a web app cannot pull up just any data from another site. This becomes a problem if you need data on someone else’s site.

Fortunately, they left an easy workaround. While a web app isn’t allowed to access the files on another site, a PHP script is. We’ll get our PHP script to do the dirty work for us and return the results to our app. The technique we will use is often called scraping.

Time to look at some code again. Here’s the App Studio part that calls the PHP script. It looks very much like the code in Ajax Made Simple. The main difference is that we’re calling a different PHP script.

Function btnGetFile_onclick()
  req=Ajax("ajaxGetURL.php/?urlToGet=" & txtURL.value)
  If req.status=200 Then 'success
    htmResponse.innerHTML=req.responseText
  Else 'failure
    htmResponse.innerHTML=req.err
  End If
  htmResponse.refresh()
End Function

Before we talk about what is going to happen at the server end, let’s see what the app looks like:

And here is what the PHP script looks like:

<?php
echo file_get_contents($_GET['urlToGet']); 
?>

Let’s take apart this one line:

  • $_GET(‘urlToGet’) gets the parameter string that was attached to the URL in our App Studio code.
  • _file_get_contents get the contents of the file, in this case, the URL that was passed.
  • echo sends the result back to our App Studio program.

Pretty simple, isn’t it?

(In this example, we’re grabbing the robots.txt file from Microsoft’s site, just to show we can get files from anywhere. Nearly all sites have a robots.txt file: it is used to guide search engines.)

Ajax made Simple Part 2: POST.

You may have read the recent blog entry called Ajax made Simple. Today we’re going to extend that a bit and talk about using the POST method.

The last blog post discussed the simplest Ajax call, which sends data to the server by adding it to the end of the URL, a method called, rather misleadingly, GET. But what if we want to send more data? GET has a limit, some say, of around 2000 characters. For more than that, we’ll use the also badly named POST method. POST has an upload limit on most servers of 8 megabytes. If you need more, server settings can be adjusted.

Let’s look at some code. You’ll see it looks very much like our last post:

Function btnAjax_onclick()
  req=Ajax("ajaxPost.php","POST",txtSend.value)
  If req.status=200 Then 'success
    htmResponse.innerHTML=req.responseText
  Else 'failure
    htmResponse.innerHTML="Error: " & req.err
  End If
End Function

The difference is a couple of extra parameters. We add “POST” and the data we want to send as a separate parameter. Before we talk about what is going to happen at the server end, let’s see what the app looks like:

OK, here is the PHP code on the server which we are calling:

<?php
 // uncomment the next line to see runtime error messages from this script
 // ini_set('display_errors','1');
 
 // Get the data from the client.
 $myText = file_get_contents('php://input');
 // Send back the text, reversed
 echo "Data received from Device (reversed):<br>" . strrev($myText); 
 
 //write the data out to a file on the server
 //make sure permissions are all OK!
 $myFile = "AjaxPost/ajaxPost.txt";
 echo "<p>Writing data to " . getcwd() . $myFile;
 $f = fopen($myFile'w'or die("can't open file");
 fwrite($f$myText);
 fclose($f);

?>

The file_get_contents(‘php://input’) call gets the data, exactly as it was sent. We’ll do two things with it: echo it back reversed and we will write it to a file on the server. The first part is easy: anything in an echo statement is sent back to our app:

echo "Data received from Device (reversed):
" . strrev($myText);

The second part involves a bit more PHP, but is straightforward. It writes the data was received to a file.

 $myFile = "AjaxPost/ajaxPost.txt";
 echo "<p>Writing data to " . getcwd() . $myFile;
 $f = fopen($myFile, 'w') or die("can't open file");
 fwrite($f, $myText);
 fclose($f);

What would you use this feature for?

  • Upload a JSON copy of your database.
  • Upload some pictures in Base64 format.
  • Create a .htm file which can be accessed as a web page.
  • Lots more ideas!

A tip on debugging PHP scripts
Since PHP scripts run on the server and not on your screen, you don’t get to see the error messages. This can make debugging difficult. If you put this statement at the top of your PHP script, the error messages will be echoed to your app:

ini_set('display_errors','1');

The error messages come back as HTML formatted text. The best way to look at them is to assign them to the innerText property of an HTMLview control.

Ajax made Simple Part 1

Most developers have heard of Ajax by now. Unless you’ve worked with it, you probably think it’s another complicated form of alphabet soup. It actually turns out to be quite easy to use from NS Basic/App Studio.

First, let’s explain what it is (and isn’t). It stands for Asynchronous JavaScript And XML. The good news is that there’s no need to be asynchronous or to use XML – and that NS Basic takes care of the JavaScript.

Ajax makes it easy to exchange data with your server. Think of it as a function you can call that is running on another system. You can pass it parameters and it can return values. Since it’s running on your server, it can do things that you cannot do on your device. It can access files and databases on the server, or get data from other web sites without worrying about Same Origin Policies.

Let’s look at some code. We will have our NS Basic app send the server a string, which the server will return reversed. Here is what the app looks like:

The only code in this app is the “Reverse” button. The Ajaxfunction sends the contents of the top textarea to a PHP script that is running on the server. If it returns successfully, we display what came back. Otherwise, we show the error:

Function btnAjax_onclick()
  req=Ajax("ajax.php/?myText=" & txtSend.value)
  If req.status=200 Then 'success
    txtResponse.value=req.responseText
  Else 'failure
    txtResponse.value="Error: " & req.err.message
  End If
End Function

The PHP script is even easier. It gets the input that is named myText, reverses it, and uses the echo statement to send it back.

<?php
 // Get the data from the client. 
 $myText = $_GET['myText'];
 // Send back the text, reversed
 echo "Data received from Device (reversed): " . strrev($myText); 
?>

Here is the result:

A few notes:

  • The php script needs to be on the same folder on the server as the NS Basic app.
  • Ajax is based on XMLHttpPost.
  • A handy way to return data from your PHP script is in JSON format. PHP even has a handy json_encode() function.

iWebInspector: Debugging on iOS devices

An amazing new product crossed my desk today. iWebInspector lets you open up a debugging session on an NS Basic/App Studio app that is running in the iOS iPhone or iPad Simulator.

It was developed by Max Firtman (who has come up with other innovations that we at NS Basic have used), based on a discovery by Nathan de Vries on how to enable the Remote Web Inspector on iOS 5.

Since the iOS Simulator only runs on Mac OS, this tool requires a Mac. You’ll also need to download Apple’s XCode, which includes the iOS 5 SDK and the Simulator. It’s a 1.6 gig download, but easy to install once it is there. You won’t have to learn XCode or even how to start the Simulator: iWebInspector will take care of that for you.

Here’s how iWebInspector looks when you start it: (this is Beta 0.9 – expect it to get better looking quickly):

If you click on Open iOS Simulator, the Simulator will start automatically. If it is purely a web app, open it in Safari then choose “Load from Safari”. If it has been saved to the Home Screen, start it and choose “Load from webapp”. PhoneGap apps can even be debugged: enter the App name and “Load”.

This tool will be especially useful for debugging apps which can only be tested on a device.

Building Native Apps

The enhancements in NS Basic/App Studio 1.3.1 make building native apps much easier. First, a bit of background: NS Basic/App Studio is designed to make Web Apps. These apps take advantage of the power of current browsers and HTML5 to make native appearing apps. With the speed improvements of JavaScript in recent years, they have excellent performance. Web Apps can also be compiled into Native Apps, which have their own advantages and disadvantages.

Under the Run menu, there is an option called “Build Native App”. Once you have tested your project, use this option to submit your app to the PhoneGap Build server. The compilers and SDKs to build native apps are large and complex: using a server to perform these operations saves you a lot of grief installing and maintaing them.

Once submitted, you can check the status of the build using “Get Native Build Status” under the Run menu.

Completed builds have their download links listed.

Some useful notes:

  • Each user of PhoneGap Build should have their own account. For demo purposes, NS Basic has a default account, but your files will not be secure there. It’s easy to sign up for your own. Once you have it, enter the information into “Deploy Options” under the Tools menu.
  • The program name and your icon will be taken from your project properties. Other PhoneGap options are set up in the configxml property in your project’s properties. Read more about using config.xml here.
  • iOS will not build until Apple’s signing information has been entered.
  • PhoneGap Build is in beta right now. PhoneGap may start charging for this service at a some point.

Getting money from your customer: PayPal

It’s easy to use PayPal with NS Basic/App Studio. You can collect the money as payments or a donations. PayPal is available in many countries. It’s much easier to set up and use than a credit card.

First, set yourself up as a PayPal Merchant. Assuming you already have a PayPal account, go to the Merchant Services tab on the main screen. On the left, you will see a tab called “Website Payments Standard”. Click on that and follow the instructions.

Once you are set up as a merchant, you will need to set up your product. The easiest way to do that is on the Merchant Services page: Choose the “Buy Now button” option. Enter a number of fields, including item name, item ID (a reference number for your own use), price, currency (21 choices!), shipping and tax info. Once complete, click on ‘Create Button’.

It will go to a new page, showing the code for the button. You’re interested in the string just after “value=”. In this case, it is “UEQCPME2W9Q8W”. Copy this number down – you will need to enter it in the IDE:

In your project, add the PayPal button like any other and position on your form. It will have the following properties:

Put the value from the PayPal screen into ‘hostedButtonID’. For TransactionType, select ‘Buy’ or “Donate’. One of the following will appear on your form:

That’s all you have to do. When your app is running, if the user clicks on the PayPal button, a new browser window will open to the PayPal page, with your product showing. All they have to do is authorize the transaction and the money will show up in your PayPal account.

If you’re running as a web app, you do not have to pay 30% to Apple. Please be careful of local tax laws and restrictions.

How to do Encryption

Encryption is easy to do in NS Basic/App Studio using an encryption library. For the purposes of this post, we’ll use the Stanford JavaScript Crypto Library. It uses the industry-standard AES algorithm at 128, 192 or 256 bits; the SHA256 hash function; the HMAC authentication code; the PBKDF2 password strengthener; and the CCM and OCB authenticated-encryption modes. Just as importantly, the default parameters are sensible: SJCL strengthens your passwords by a factor of 1000 and salts them to protect against rainbow tables, and it authenticates every message it sends to prevent it from being modified.

First step is to add the library to your project. You can follow the steps here, or simply export and import the library from the Encrypt sample.

Encryption works by supplying a password which is used to scramble the text in such a way that it is virtually impossible to unscramble without that password.

There are two important functions: encrypt(password, text) and decrypt(password, text).

Here is how you would use them in a program:

Function btnEncrypt_onclick()
  txtEncrypted.value=sjcl.encrypt(txtPassword.value, txtPlain.value)
End Function

Function btnDecrypt_onclick()
  txtPlain.value=sjcl.decrypt(txtPassword.value, txtEncrypted.value)
End Function

sjcl is the reference to the encryption library. It is created as a result of the inclusion of the library in the project. Once your data is encrypted, you can save it to a database or send it to another computer.