setInterval not working in iOS 8 – Home Screen Apps Lose Timing Functions After Lock/Wake

ios_8_logo

If your application is being used as a homescreen web application, you’ll find yourself in a sorry state. Of course, any web app can be converted into a home screen app by the user, so I guess technically this affects anyone making a remote web application. This bug is easily reproduced by simply calling setTimeout(callback, 1) or requestAnimationFrame(callback) via some button or event. When you first open your application, you’ll notice all timing functions are working fine. However if you lock your phone and then unlock to return to your application, you’ll see none of the timing functions can call callbacks anymore. They are simply broken at a native level. There is no reset, no bringing your application back to life, it’s a kill it and restart situation.

These timing functions are crucial to pretty much every other JavaScript framework/library ever made. Definitely head over to Apple as soon as you can, and let them know that you would like to have all of your JavaScript functions, all the time.

Radar Bug Report: http://www.openradar.me/radar?id=5895945212395520

 

Alternative to setInterval and setTimeout

JavaScript’s setTimeout and setInterval are evil and not precise…

  1. both have a delay of various milliseconds http://www.andrewduthie.com/post/a-self-correcting-setinterval-alternative/
  2. both are very resource intensive as they execute several times every second.

A new alternative is requestAnimationFrame. it’s less resource=intensive, does not slow down other stuff and it is disabled on page blur.

This makes it the perfect substitute for a modern setTimeout and setInterval.

So I wrote this functions:

Description

This functions use requestAnimationframe to check if the time is passed based on the elapsed Time calculated from Date.now. The time passed is more precise than the native functions and theoretically less resource intensive. Another advantage/disadvantage(depends) is that the functions are not executed on page blur.

Good for: animations, visual effects

Bad for: timers, clock

RafTimeout

window.rtimeOut=function(callback,delay){
 var dateNow=Date.now,
     requestAnimation=window.requestAnimationFrame,
     start=dateNow(),
     stop,
     timeoutFunc=function(){
      dateNow()-start<delay?stop||requestAnimation(timeoutFunc):callback()
     };
 requestAnimation(timeoutFunc);
 return{
  clear:function(){stop=1}
 }
}

RafInterval

window.rInterval=function(callback,delay){
 var dateNow=Date.now,
     requestAnimation=window.requestAnimationFrame,
     start=dateNow(),
     stop,
     intervalFunc=function(){
      dateNow()-start<delay||(start+=delay,callback());
      stop||requestAnimation(intervalFunc)
     }
 requestAnimation(intervalFunc);
 return{
  clear:function(){stop=1}
 }
}

Usage

var interval1,timeout1;
window.onload=function(){
 interval1=window.rInterval(function(){console.log('interval1')},2000);
 timeout1=window.rtimeOut(function(){console.log('timeout1')},5000);
}

/* to clear
interval1.clear();
timeout1.clear();
*/

Demo

http://jsfiddle.net/wZ9Z6/

Advertisements

Generating Signing Keys for Apple iPhone Phone Gap Builds

When you are building applications that should work across multiple platforms using Phone Gap, you will need to generate a set of signing Keys to work with the different platforms:
Keys

Generating a Key for Apple iOS from MacOS

To manually generate a Certificate, you need a Certificate Signing Request (CSR) file from your Mac. To create a CSR file, follow the instructions below to create one using Keychain Access.

Create a CSR file.

In the Applications folder on your Mac, open the Utilities folder and launch Keychain Access.

Within the Keychain Access drop down menu, select Keychain Access > Certificate Assistant > Request a Certificate from a Certificate Authority.

  • In the Certificate Information window, enter the following information:
    • In the User Email Address field, enter your email address.
    • In the Common Name field, create a name for your private key (e.g., John Doe Dev Key).
    • The CA Email Address field should be left empty.
    • In the “Request is” group, select the “Saved to disk” option.
  • Click Continue within Keychain Access to complete the CSR generating process.

Generating a Key for Apple iOS from Windows

I have a Windows computer and I found it very hard to generate a key. If you follow the steps below, you might find it easier:

  1. Install Visual C++ 2008 Redistributables
  2. Download Open SSL for Windows. http://slproweb.com/products/Win32OpenSSL.html and install it onto c:OpenSSL-Win32
  3. Make sure the bin folder is installed in c:OpenSSL-Win32bin
  4. Change your PATH variable to have this path:
    • Select Computer from the Start menu
    • Choose System Properties from the context menu
    • Click Advanced system settings > Advanced tab
    • Click on Environment Variables, under System Variables, find PATH, and click on it.
    • In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
  5. The first thing you need to do is generate a private key. Go to the command line and navigate to whatever directory you want to store the generated files in. Then type in the following to generate the key:
    openssl genrsa -des3 -out ios.key 2048

    Keys2
    The result will be a new file called “ios.key” in this folder.

  6. Next you need to generate a Certificate Signing Request or CSR file. You can do this by running the following command, which uses the ios.key file generated earlier:
    openssl req -new -key ios.key -out ios.csr -subj "/emailAddress=contact@carra-lucia-ltd.co.uk, CN=CARRA-LUCIA-LTD, C=UK"

    Change the items in red to match your needs.
    Keys3

  7. Now you need to go to your Apple Developer iOS Provisioning Portal in order to generate an iOS Development Certificate, using the ios.csr file you’ve just generated. Click on “Certificates” in the left hand side, and then “Request”.
    iOSCertificatesAdd Ios Certificate

    You will be prompted to upload a .csr file, and then wait for the certificate to be issued, which it will quite quickly, refresh the browser if you need to.
    csr file

  8. Now download the development certificate that was issued and save it in the same directory where the other generated files are.
    app_distribution
  9. You now need to convert it to a PEM file which you can do with:
    openssl x509 -in ios_distribution.cer -inform DER -out ios_distribution.pem -outform PEM

    Where ios_development.cer is the name of the development certificate created on the Apple Provisioning Portal and ios_development.pem is the PEM file that we want to generate.

  10. Next file is the P12 file, which uses both our private key (ios.key) and the iOS distribution certificate (ios_distribution.pem):
    openssl pkcs12 -export -inkey ios.key -in ios_distribution.pem -out ios_distribution.p12

    You will be asked to enter the access phrase for the ios.key file (which you noted from earlier) and you will need to generate an export password for the P12 file and verify it. The ios_distribution.p12 file is then generated.
    keys4

  11. The last file you need to generate is the provisioning profile, which again requires you to return to the Apple Provisioning Portal.
    iOsProvisioning
  12. If you plan to use services such as Game Center, In-App Purchase, and Push Notifications, or want a Bundle ID unique to a single app, use an explicit App ID. If you want to create one provisioning profile for multiple apps or don’t need a specific Bundle ID, select a wildcard App ID. Wildcard App IDs use an asterisk (*) as the last digit in the Bundle ID field. Please note that iOS App IDs and Mac App IDs cannot be used interchangeably.
  13. Select the certificates you wish to include in this provisioning profile. To use this profile to install an app, the certificate the app was signed with must be included.
  14. Bear in mind that such certificates need to be tied to your iOS testing devices via their UDIDs, and again there is documentation on how to do this.
    provisioning profile
    Once the provisioning profile is generated, download it (e.g. iOS_Development.mobileprovision) and save it in the same place as the other files. This file will also need to be installed on each of your iOS testing devices.

You should now have everything that you need to generate an iOS signing key for PhoneGap Build:

  • P12 certificate file
  • provisioning profile
  • certificate password

These steps can also be used to generate a distribution key for the iTunes Store.

Run iPad Web Application Full Page (Bookmark)

Building an iPhone or iPad Web App is not an easy endeavor. However, if you have any experience in HTML 5, Javascript and CSS its a lot easier to accomplish than you would think. Apple has built a lot of tags and templates into the building of there mobile safari browser. I am going to go over many of the things that I have found that have really helped me build my webapp.

Meta Tags Used By Mobile Safari

To make your app full screen when it is added to the iPhone /iPad home screen using the + button on the browser, the below meta tag will remove all buttons and the url bar and will give it the “native” app look that we are going after. To use any of the meta tags below just add them somewhere in your head tag.

<meta name=”apple-mobile-web-app-capable” content=”yes” />

Now when you pinch on the app it will still zoom and scale. Now, native apps will not zoom or scale, so when need to do something to stop that. Luckily Apple has designed a Meta tag to do that also..

<meta name=”viewport” content=”user-scalable=no, width=device-width” />

The last thing that you may notice is when you tug the app up or down it kinda zooms down and you can see the “background” of the browser. Apple has also designed a meta tag to get rid of that. However, you do need to add a tag to your body tag also. Below is an example…

//

Making Links Open Fullscreen and Not In Safari

Now this was one of the most frustrating problems I had with making my web app in the beginning. If you use…

<a href=”link.html”>Your Link</a>

that tag will take you straight out of your fullscreen app and right into the normal safari, we don’t want that. So the solution to get past this is to use a little bit of Javascript. Now, how we would do this using the Javascript is below…

<a ontouchstart=”window.location=yourlink.html’ “>Your Link</a>

Now some of you familiar with Javascript will see that we are using the ontouchstart instead of onclick. This is a iPhone/iPad only event trigger that will only work on iOS devices. Its a lot smoother on iOS devices but will not work on computers. You can use that event trigger anywhere in your web app. Since onclick takes about one extra second for the device to read, ontouch start is a great asset to have on our side.

IOS7 and above – Show Links in App

if((“standalone” in window.navigator) && window.navigator.standalone){

var noddy, remotes = false;

document.addEventListener(‘click’, function(event) {

noddy = event.target;

while(noddy.nodeName !== “A” && noddy.nodeName !== “HTML”)

{ noddy = noddy.parentNode; }

if(‘href’ in noddy && noddy.href.indexOf(‘http’) !== -1 && (noddy.href.indexOf(document.location.host) !== -1 || remotes))

{ event.preventDefault(); document.location.href = noddy.href; }

},false);
}

Specifying a Webpage Icon for Web Clip

You may want users to be able to add your web application or webpage link to the Home screen. These links, represented by an icon, are called Web Clips. Follow these simple steps to specify an icon to represent your web application or webpage on iOS.

  • To specify an icon for the entire website (every page on the website), place an icon file in PNG format in the root document folder called apple-touch-icon.png
  • To specify an icon for a single webpage or replace the website icon with a webpage-specific icon, add a link element to the webpage, as in:
    <link rel="apple-touch-icon" href="/custom_icon.png">

    In the above example, replace custom_icon.png with your icon filename.

  • To specify multiple icons for different device resolutions—for example, support both iPhone and iPad devices—add a sizes attribute to each link element as follows:
    <link rel="apple-touch-icon" href="touch-icon-iphone.png">
    <link rel="apple-touch-icon" sizes="76x76" href="touch-icon-ipad.png">
    <link rel="apple-touch-icon" sizes="120x120" href="touch-icon-iphone-retina.png">
    <link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad-retina.png">

    The icon that is the most appropriate size for the device is used. If no sizes attribute is set, the element’s size defaults to 60 x 60.

If there is no icon that matches the recommended size for the device, the smallest icon larger than the recommended size is used. If there are no icons larger than the recommended size, the largest icon is used.

If no icons are specified using a link element, the website root directory is searched for icons with the apple-touch-icon... prefix. For example, if the appropriate icon size for the device is 60 x 60, the system searches for filenames in the following order:

  1. apple-touch-icon-76×76.png
  2. apple-touch-icon.png

See “Icon and Image Sizes” for webpage icon metrics.

Now what if your user wants to take a certain element and drag it around with there finger? How are we going to do this? Well the technique that I am using is called Drag Drop Library. Its very simple to use, go to this website http://www.gotproject.com/blog/post2.html, download their javascrupt Library using the green button. Then link to that JavaScript file on any page where you would want to use drag and drop. Now, the syntax for getting an element to be able to be dragged is below…

  • //To make an element draggable
  • var D = new webkit_draggable(‘id_of_element’, {options});
  • //To stop an element from being draggable
  • D.destroy();

So what you are going to do is give an element that you want to be able to be dragged a unique ID using css. Then take that css and input it into the above code that reads ‘id_of_element’. So that sample code would find and html element that has a id=”id_of_element” and make it be able to be dragged around by the users finger. It’s fairly simple and creates an awesome “WOW” affect with your apps.

iPhone and iPad web apps are slowly becoming more wide spread around the world. Especially now that Apple is finally giving us Web Designers and Developers the required tools. Now every iOS developer doesn’t have to be an Obj C wizard and have a mac, any person with a little HTML know how can create easy, good looking apps.

Getting iPad Web App to Work Offline Using Localhost, not Cache-Manifest

I spent so much time looking around trying to figure out how I was going to get my web app to work offline. My client will be using the app at large conferences to showcase there product and give a presentation. Wifi is very very unstable at large conferences so it is necessary to make it work offline. What I finally decided to do was to Jailbreak each iPad, and install a server on the localhost of the iPad. To do that I used a program on Cydia called PHPod. This creates a server on that iPad and gives me access to files stored directly on the iPad. What I did next was SSH into the iPad and copy my entire Web App into the WWW directory. Next, I went to localhost on safari on the iPad, clicked my web app and boom there it is right on the iPad. It runs fast, my JQuery still works, all my forms work, its perfect. Now I am looking to make my own Cydia repo where I can host the web app so that the clients wont have to ssh into the iPad every time there is a change. It will just update the package and the site will be updated by the Repo. Yes there is the option to use Cache Manifest and all that but it doesn’t really work all the time and there’s a limit so I couldn’t cache all my videos and larger files etc.

Business Processes in Practice: Make-to- Stock vs. Make-to-Order (Apple Case Study)

dell-vs-appleA good example of a company that uses the make-to- stock strategy is Apple Inc. Apple uses the make- to- stock process for Macs sold in its Apple stores. The company first estimates the consumer demand for its Mac computers. It then calculates its available  manufacturing capacity and the quantities of raw materials it will need to build enough computers to meet consumer demand. Apple’s strategy is to purchase raw materials and reserve manufacturing capacity ahead of time to maximize the cost efficiencies of buying materials in bulk quantities and doing large production runs. Apple and its contract manufacturers then produce a specific quantity of each Mac model and ship them from the factory to the Apple stores and other retail outlets for sale. When customers come into an Apple
store, they expect that the computer they want to buy will be there and that they can take it home immediately after purchasing it.

 

Because Apple uses a make-to-stock strategy, the company must pay extremely close attention to both its retail sales and the amount of finished goods inventory it has in stock in order to estimate its demand as accurately as possible. If Apple overestimates the demand for a particular product, the company will be stuck with a large inventory of very expensive finished goods that customers
don’t want to buy and that will decrease in value while they sit on the shelf. Conversely, if it underestimates the demand for a product, customers who want to purchase the computer will be told it is out of stock. They will then have two options: place a back order and wait until the store gets resupplied with inventory, or shop for the product at a different store. Either outcome will make consumers unhappy and could result in lost sales.

In contrast, one of Apple’s major competitors— Dell—employs a make-to-order production strategy. Dell was the first company in the industry to build computers only after they had received a fi rm order and thus knew exactly what product the customer wanted. Because Dell does not have many retail outlets like Apple (although it has recently tested some retail partnerships), the company
relies primarily on telephone and Internet sales channels for the majority of their sales. In contrast to Apple customers, then, when Dell customers place an order, they anticipate that they will have to wait a few days for the computer to be produced and delivered.
After the customer places an order, Dell typically assembles the computer from raw materials it has on hand and then ships it directly to the customer.
Unlike Apple, then, Dell does not need to be very concerned with estimating demand for its finished products because it knows exactly what customers want based on customer orders. However, Dell must be extremely careful in purchasing raw materials and managing its production capacity. Because its production runs are very small—sometimes one computer at a time—it must estimate its raw material needs and production scheduling based on an unknown customer demand.
If Dell mismanages its production planning process, it is especially susceptible to an oversupply or undersupply of raw materials and shortages or idleness in production capacity. If Dell does not have sufficient raw materials or production capacity, customers will have to wait much longer for their computers to be shipped.
Conversely, if the company has excessive raw materials or unused production capacity, it loses money.
Although Dell’s customers are accustomed to waiting a few days for their computers to arrive, they probably will be upset if their deliveries are delayed for several weeks due to a shortage of raw materials or a backlog of production orders. Alternatively, Dell’s profitability will suffer if its production lines are idle or its warehouses are filled with unused raw materials.
Both Apple and Dell have chosen a production strategy that maximizes their profitability. Apple believes that by controlling the entire buying experience through their Internet and physical stores, they can attract more customers. This strategic objective drives Apple to place a much higher emphasis on having products available in the store when a customer comes there to shop, which increases the likelihood that she or he will make a purchase. In addition, Apple realizes significant cost savings through large, planned production runs and close coordination with retail sales data generated by their online and physical stores. For all these reasons, the make-to-stock production process is probably the best strategy for both Apple and its customers.
In the case of Dell, the make-to-order production process fits well with the company’s rapid assembly and standardized products. Dell’s customers are comfortable ordering a computer that they have never seen because they know that Dell uses high-quality, industry-standard components. They also trust Dell to ship them a finished computer in just a few days, and they are willing to wait
for it to arrive rather than pick it up in a store.

In essence, the preferences and behaviors of each company’s customers determine, to a great extent, the production process for each company. Apple’s customers want to touch and experience the product in a retail store, whereas Dell’s customers are content to
buy something over the phone or the Internet. Each company has optimized its production process to match both its specific set of customer requirements and its internal profitability goals and cost structure.

Source: Adapted from Magal and Word Essentials of Business Processes and Information Systems. John Wiley & Sons, Inc. (2009).