Smartphone Challenge: Guidelines for development of network friendly applications


Published on

Published in: Technology, Business
1 Comment
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Smartphone Challenge: Guidelines for development of network friendly applications

  1. 1. GSM Association Non ConfidentialOfficial Document <WG.NN> Smartphone Challenge: Guidelines for development of network friendly applications Version 0.1 21st September 2011This is a Non Binding Permanent Reference Document of the GSMA.Security Classification – NON CONFIDENTIAL GSMA MATERIALCopyright NoticeCopyright © 2011 GSM AssociationAntitrust NoticeThe information contain herein is in full compliance with the GSM Association’s antitrust compliance policy.<V0.1> Page 1 of 61
  2. 2. GSM Association Non ConfidentialOfficial Document <WG.NN>Table of Contents 1  Introduction 4  1.1  Overview 4  1.2  Scope 5  1.2.1  Who should read this document 5  1.2.2  Organisation of the document 6  1.3  Definition of Terms 6  1.4  Document Cross-References 6 2  Network friendliness 7  2.1  Constraints in mobile broadband 7  2.2  Smooth user experience 8  2.2.1  Asynchrony 8  2.2.2  Non-blocking user interface 9  2.2.3  Offline mode 11  2.2.4  Bandwidth awareness 11  2.3  Efficient network connection usage 11 3  Ideal mobile application 15  3.1  Asynchrony 15  3.2  Connection loss and error handling 15  3.3  Caching 18  3.4  Security 22  3.5  Efficient traffic usage 24  3.5.1  Cloud-based transformations, 24  3.5.2  Media Transcoding 25  3.6  Compression 26  3.7  Background / Foreground modes 27  3.8  Application Scaling 29 4  Detailed Recommendations 30  4.1  iOS 30  4.1.1  Asynchrony 30  4.1.2  Connection loss and error handling 31  4.1.3  Caching 32  4.1.4  Security 34  4.1.5  Data formats 35  4.1.6  Compression 37  4.1.7  Background / Foreground modes 37  4.2  Android 40  4.2.1  Asynchrony 40  4.2.2  Offline mode 43  4.2.3  Caching 44  4.2.4  Security 46  4.2.5  Data formats 47  4.2.6  Compression 48  4.2.7  Background / Foreground modes 48  4.3  Windows Phone 49  4.3.1  Asynchrony 49  4.3.2  Connection loss and error handling 54  4.3.3  Caching 57  4.3.4  Security 58  4.3.5  Data formats 59  4.3.6  Compression 59  4.3.7  Background / Foreground modes 60 <V0.1> Page 2 of 61
  3. 3. GSM Association Non ConfidentialOfficial Document <WG.NN>5  References 61 Document Management 61  Document History 61  Other Information 61 <V0.1> Page 3 of 61
  4. 4. GSM Association Non ConfidentialOfficial Document <WG.NN>1 Introduction1.1 OverviewThe unexpected explosion in the use of data connectivity has taken key industrystakeholders by surprise, in particular network operators who are at the forefront ofdelivering services to customers. This is good news for the industry as a whole as a newdawn of growth and development is at last on the horizon.Nevertheless, the good news is marred by a number of challenges facing network operatorsin sustaining the anticipated growth.A consequence of this success is a greatly increased signalling load at the network levelcompared with a relatively low amount of data traffic. End-users and application developersare impervious to the network’s increased signalling load as it is only visible to networkoperators/service providers. Nevertheless, a great majority of smartphone users experienceless than desired overall user experience in terms of rapid battery drainage, unresponsiveuser interface with seemingly slow network access, non-functional applications, etc.With the launch of 3rd generation cellular networks almost 10 years ago, most industrypundits were toying with a variety of ideas to explain what the possible killer applicationwould be (beyond mobile voice call). However this killer application failed to emerge andinstead the focus shifted to identifying a collection of services that it was hoped would inturn deliver truly compelling mobile applications.Around the same time the term ‘smartphone’ was coined by the mobile industry: a phonesufficiently smart and intelligent that it would be able to act as a Personal Assistant (PA) tothe user by offering a variety of data based services all available at the push of a button.However the failure to deliver on this promise lead to some scepticism from industrycommentators at the time.Nevertheless internet connectivity on notebooks/laptops has increased markedly over timeto the extent that network operators were convinced they would deliver the right level ofincrease in data connectivity for the mobile industry. That meant tuning the mobile networkto cater for browser based internet connectivity and mobile email applications (which do notplace a heavy burden on the mobile network in terms of signalling).More recently the emergence of popular smartphones has posed a challenge for the mobilenetwork as the network signalling load that they generate is significantly higher. This isdriven by a number of factors, one of which is that all aspiring enthusiasts (perhaps with abackground in developing desktop applications) to develop their ideas into networkunfriendly applications that can be easily installed on smartphones.As a result, a key symptom driving change in the industry’s landscape is the unprecedentedsignalling load faced by network operators which is out of proportion to the level of datausage and the generated revenue.Subsequently, the industry has responded by introducing the ‘fast dormancy’ concept in linewith the 3GPP standard where the handset is allowed to determine its own sate and requestits release of the network connection. This has been implemented in what is known as3GPP release 8. However, fast dormancy can be used intelligently to ensure optimum useof the functionality.In addition to using fast dormancy intelligently there are a number of other aspects relatingto the development of network-friendly smartphone applications that need to be considered: a) Optimal use of target platform functionality by 3rd party developers  Leads to better bandwidth usage b) Competent development of 3rd party applications that are user and network friendly<V0.1> Page 4 of 61
  5. 5. GSM Association Non ConfidentialOfficial Document <WG.NN>  Provides a much improved user experience that is optimal to the target platform and cellular connectivity including efficient battery usage c) Identifying gaps in smartphone software platforms  To improve performance in terms of network/user friendlinessThis document will focus on items ‘a’ and ‘b’, where a number of key concepts in applicationdevelopment for mobile terminals are explored and pitfalls identified in general terms as wellas per target platform. The study covers iOS, Windows Phone and Android.1.2 ScopeThis document is meant to provide as much information as possible to encourage a betterapproach in developing mobile applications that work with network.In writing the document, popular applications on 3 leading mobile platforms and theircommon use case scenarios have been analysed, focusing on bottlenecks and commonmistakes. The outcome has been aggregated with a view to developing generic architecturalguidelines and recommendations on best practices. The document attempts to increaseawareness of specifics of mobile networks and explain why network applications aredifferent to those which work with local data and why developers should take extra careworking with the cellular network. In addition, specific recommendations are made for eachplatform under consideration.By following the guidelines and recommendations in this document developers are betterequipped to create fit-for-purpose applications; mobile operators will see a reduced strain onnetwork overload and end users will experience more responsive and reliable applications.Developing network efficient applications will benefit developers by: - Improving the overall user experience of network applications, particularly, making them more responsive, providing more control to users - Improving reliability in the unreliable mobile network environment - Providing better user satisfaction by reducing consumption of traffic, which can result in lower customer bills; and also improved battery life of the deviceThe scope of the detailed recommendations is limited to the three platforms, namely iOS,Android and Windows Phone 7. However, the theoretical part of Sections 3 and 4 aregeneric; they can be applied to any platforms.It is worth noting that the document does not cover: - Generic user interface guidelines - Device security - Back end implementation - High level of security which is required in rare cases for specific applications such as banking or enterprise systems - Web applications (HTML 5)1.2.1 Who should read this documentThe document does not explain the basics of developing of mobile application and it isaimed at developers who are able to develop or intend to develop network dependantapplications. The recommendations in Chapter 4 “Detailed Recommendations” are meant toimprove quality of applications relying on cellular network connectivity and how to overcomechallenges that mobile networks introduce.<V0.1> Page 5 of 61
  6. 6. GSM Association Non ConfidentialOfficial Document <WG.NN>1.2.2 Organisation of the documentSubsequent chapters are organised in the following order. Section 3 provides the relevant background and lays down the fundamental concepts of the mobile network constraints that are generic to all platforms. Section 4 will follow the theme by considering what an ideal application/platform should be in terms of its characteristics to ensure it is user and network friendly. Section 5 will map the outcome of all preceding chapters to target platforms where specific functionality or limitations are highlighted to assist developers.1.3 Definition of TermsTerm Description1.4 Document Cross-References DocumentRef Number Title<V0.1> Page 6 of 61
  7. 7. GSM Association Non ConfidentialOfficial Document <WG.NN>2 Network friendlinessNowadays, regardless of different technology standards, the underlying technologiessupport packetized data connectivity and increased data bandwidth for consumers.Commonly known as mobile broadband the available bandwidth can range anythingbetween around 9.6kb/s and up to 14.4 Mb/s downlink. However, despite the increasedbandwidth mobile networks differ from broadband in most cases – they are less reliable andhave limited variable bandwidth, higher latency, and a non-permanent communicationchannel. Loss of connectivity to the Internet is considered as the normal situation. Batteryresource is precious and continuous use of the network reduces the operation time ofdevices dramatically.By contrast, fixed line broadband connectivity based on cable-modem or ADSL/DSLtechnologies is well established. It provides a consistent data connection of up to 50 Mb/sdownlink due to deploying relatively less complex technologies and the limited terminalmobility it offers.Mobile networks in comparison to the fixed broadband lines, have their own specificrequirements and constraints that should be taken into account at the design anddevelopment stages. These constraints are described in the following section.2.1 Constraints in mobile broadbandThe very nature of mobile broadband access imposes a number of constraints on themanner in which it may be used.  Limited bandwidth: Available bandwidth for cellular networks may vary depending on the geographic coverage and underlying technologies used. On average it is much lower than Wi-Fi connections. When on the move, the bandwidth can dynamically step down.  Data is not always free: Mobile data traffic can be expensive particularly when roaming. It may mean high bills for the consumers, thus requiring careful consideration in any service deployment.  Battery life: Mobile terminals, although small, are a feast of technologies miniaturised into a small physical space powered by a battery. When in full operation, it runs not only a processor with an active screen, but also data communication over cellular network that can significantly impact the battery life. Transferring large amounts of data via cellular network puts the radio access into high drive mode; it can drain the battery fully in collaboration with the active colour screen in matter of few hours. The more careful the use of network, screen and processor resources, the longer a device can be used on a single charge.  Network reliability: Mobile cellular networks cannot by nature guarantee reliable connectivity at all times. This is mainly due to blind spots in mobile coverage and the limitations of deployed technologies, in particular when the user is on the move. Roaming between cells or moving in heavily built up areas can result in lost packets, increased latency, reduced network speed, often losing connectivity completely. However these are simply a normal part of a mobile terminal’s daily usage patterns.  Security: As users do not always have direct control over their wireless networks, they can be connected to public Wi-Fi hotspots or even to spoofed networks, meaning that user’s privacy can be compromised or identity stolen. Hence, developers should not assume that wireless networks are secure. Authentication, secure protocols and a cautious approach to content transmission should be adopted in all development.<V0.1> Page 7 of 61
  8. 8. GSM Association Non ConfidentialOfficial Document <WG.NN>When network communication is optimized, the overall user experience is greatly improvedand therefore all possible methods of optimal data transmission should be adopted (efficientprotocols, caching, compression, data aggregation, etc.).Although many customers have access to more reliable Wi-Fi networks at home, work orpublic places, the primary access to the Internet is via cellular network. Developers often donot take this into account and do not perform field testing of their applications, hopinginstead that customers will find a reliable connection somehow. Development in simulatedenvironments running on fast and well connected laboratory machines may never uncoveruse cases experienced in real life and therefore day to day testing on a device connected tocellular network is essential.2.2 Smooth user experienceAlthough, network efficiency may be understood as an efficient usage of traffic, it is alsoimportant to pay attention to the reality of mobile devices and mobile networks. In particularit is a common experience that the connection can be lost or data transfer delayed. Theuser experience of network friendly applications should be adjusted accordingly with theview to smooth the impact of such problems.2.2.1 AsynchronyThe first assumption to be made is that any response in mobile network might be delayed ornot delivered at all. To ensure a smooth user experience, an application’s architectureshould not solely rely on a sequence of responses, but be ready to deliver results to the enduser even if not all the data has arrived.To explain the problem in general terms, consider the simple example of a basic item listwhere thumbnails are used to show how network requests can be handled. Figure 1 showsthe sequence of requests required to download if all requests had been madesynchronously: Figure 1 – Synchronous requestsIn this example the list contains 3 items with a thumbnail image for each item.If the same requests were sent in parallel, then the timeline will be as shown in Figure 2: Figure 2 – Asynchronous requestsShould the network connection be reliable with constant speed, the end user will not noticethe requests had been sent in parallel. The overall loading time will not show a tangibledifference. However, such an arrangement can only exist in ideal networks where nolatencies and connection interruptions are prevalent.<V0.1> Page 8 of 61
  9. 9. GSM Association Non ConfidentialOfficial Document <WG.NN>In reality however, the same sequence can result in the arrangement in Figure 3, where animage that has been requested earlier may be received much later and some requestsmight not receive any responses at all. Figure 3 – Asynchronous requests in realityIf an application waits to receive every single response and does not progressively showresults to the end user before completion of the entire cycle (as described above), it is clearthe user might not see anything whatsoever, facing a blank page instead.This simple example demonstrates a few important considerations that should be taken intoaccount when architecting applications that rely on mobile network connectivity. 1. Network connections should be arranged in an asynchronous manner; meaning they should not be in the same thread with user interface. This separation will ensure that delayed responses will not block the user interaction entirely. 2. Where possible, the end user should see the progress of data loading. This could be done by using progress bars, placeholders or a simple network indicator. In our example, text information can be displayed already when the list is loaded without waiting for images to arrive. As soon as an image is loaded it can be displayed immediately (see Figure 4 below) Figure 4 – Timeline of asynchronous request 3. Applications should assume that any of the requested responses may fail to arrive and an appropriate user interface should keep the user informed of the progress in a manner that softens the impact without appearing as if the software has crashed or hung.2.2.2 Non-blocking user interfaceA blocking User Interface (UI) is an instance of user interaction where the user is faced witha single UI element while all other functionality is disabled. These normally pop up from an<V0.1> Page 9 of 61
  10. 10. GSM Association Non ConfidentialOfficial Document <WG.NN>application as soon as there is a delay in receiving relevant data, or when the applicationlogic’s decision tree is unable to proceed because it has encountered a missing data item.However, in reality there are a very few cases where the network interaction should blockthe user from initiating any other operations. For example, when on a login page, a usercannot progress any further until access is granted. However, even here it should bepossible to cancel signing in if a mistake has been spotted in the entered data (or pass thecontext to another application such as the phone dialler).In most cases, network operation should be completed in the background, allowing user tocancel or switch to other views. It is inappropriate to allow a web browser to block thescreen with the message “Loading” until the whole page is loaded. Figure 5 – Non-blocking user interface examplesWhen designing an application’s UI and its decision making tree it is important to distinguishbetween a user initiated network connection and that of performing a secondary functionthat is not explicitly requested by the end user. This may define how user should be notifiedof the progress and errors relating to the operation.For example, if the user requests a web page to be loaded and the browser fails to connectto the server, then a modal error message should be displayed. However, if a secondarycontent such as image has not been delivered, then there is no point in showing a modalerror message for each picture item, it would be more sensible to show placeholders withbroken images instead.Another good example of showing unhelpful error messages is that of untimely and out ofcontext error messages, something that appears in some offline games. Whenever, thesegames are launched with no network activity, an error message is often shown that reads“Could not connect to server”, probably as a result of failure to send game statistics back tothe server. The user is not even waiting for any result from server at this point in time andany untimely, irrelevant message can create an unnecessary break in the user experience.<V0.1> Page 10 of 61
  11. 11. GSM Association Non ConfidentialOfficial Document <WG.NN>2.2.3 Offline modeThere are many occasions when a mobile terminal cannot be connected to the network forsome reason. As a developer, it is important to factor in the following problems in thearchitecture design: 1. On loss of network connection, the end user should understand the reason why an operation could not be completed. 2. To prevent data loss (due to limitations of devices and networks), it is very important to provide functionality to save the current data with the option to retry/resume the activity at a later time. - Examples of user disappointment include losing long text string that had been typed on a small mobile keyboard when it is clear the application cannot send the text to the server; or when, after downloading a huge chunk of data, it is not possible to resume downloading and the whole process needs to be started all over again. 3. The user should be notified of any functionality that is not available in the offline mode. 4. It is far more desirable to allow users, if possible, to continue using an application with data stored in offline mode for later synchronisation when network connection has reestablished. 5. The application can also scan for data connectivity in background mode without affecting operation in offline mode.A number of mechanisms are proposed in this document as possible solutions foraddressing the issues highlighted above.2.2.4 Bandwidth awarenessApplications with excessive network dependency, such as audio or video streaming, requirean assured level of data transmission speed. Considering that a variety of wirelesstechnologies such as GPRS, EDGE, 3G or Wi-Fi may be in use, it would be sensible tocheck first what underlying carrier is in use in order to request an appropriate quality ofcontent from the server; and notify user about the possible additional cost of using mobiledata. If the application needs a more precise estimation of speed, then it would bereasonable to measure or dynamically adjust the quality of streamed data according tolatencies.Furthermore, the application should be capable of monitoring changes to carrier and dataspeed at any given time, due to, for example, users leaving a Wi-Fi Hotspot or a cellularhandover such as 3G to GPRS taking place due to poor signal quality.2.3 Efficient network connection usageWe have already highlighted the constraints and limitations of wireless technologies.Operating within these limitations means the frugal use of data upload/download that alsohas a monetary impact when roaming.An obvious limitation to bear in mind of is the amount of data transferred which impacts onthe cost of the data plan, especially in roaming, user experience responsiveness and batterylife. Any optimization of traffic will be appreciated by end users, so double check if allnetwork transfers are really necessary, protocols are chosen optimally and that caching isused appropriately.Apart from data traffic, there are a few hidden pitfalls in the 3G network that may causeadditional inconveniences. These lie in the implementation of Fast Dormancy which tries to<V0.1> Page 11 of 61
  12. 12. GSM Association Non ConfidentialOfficial Document <WG.NN>minimise network signalling and battery consumption, both important problems given theincreasing number of smartphones and online applications.When a device requests sending/receiving data over the cellular network, it switches into adedicated channel state that consumes about 60-100 times more power compared to theidle mode. However, the process of switching between states requires sending networksignals that also take a certain amount of time. For example, switching from Idle toDedicated Channel (DCH) should exchange 24-28 signals taking about 2 seconds. The costof switching between states excludes the option of disconnecting the device immediatelyafter finishing every network connection. Keeping the device in a high power state also isnot an option as it will drain the battery rapidly.Between the Idle and Dedicated Channel states there are few more states that come intouse. Fast dormancy technology defines an algorithm that dictates when a device can beswitched to lower state after the last data transmission. Figure 6 below shows how thepower drops after a certain period of inactivity in data transfer. Times T1 and T2 are networkdependent. Figure 6 – Power Consumption – Example 1<V0.1> Page 12 of 61
  13. 13. GSM Association Non ConfidentialOfficial Document <WG.NN>Once the state has switched to the lowest, establishing a new data connection will need toexchange about 24-28 signals with the network which takes about 2 seconds.Considering this behaviour we can consider the case when the application has many shortconnections over a specific period of time: Figure 7 – Power Consumption – Example 2Areas filled in red in Figure 7 shows the overhead in battery usage compared to thescenario presented on Figure 8 where all data connections were synchronised andcompleted in the same time. Figure 8 – Power Consumption – Example 3Although, most the timers and conditions of switching between the cellular states arenetwork dependant, it is good to know to at least example of approximate characteristics.According to tests that have been done by XMPP,<V0.1> Page 13 of 61
  14. 14. GSM Association Non ConfidentialOfficial Document <WG.NN> - Dedicated channel (the highest level) consumes about 380mA which can drain average Android device or iPhone battery within less than 4 hours. Time before dropping to lower state is ~8 seconds - FACH (shared channel – intermediate level) consumes about 140mA. In order to keep this state and prevent switching into the higher power mode, the packet sizes must be around 128 bytes and after deducting TCP and TLS overheads it leaves only about 70 bytes of actual data. Timeout before switching to lower state is around 8 seconds. Battery life can reach maximum 7 hours in this mode.In summary, the general recommendation for developers is to transfer data in one go anddo not spread network activities, whenever it is possible.ReferencesXMPP on Mobile Devices<V0.1> Page 14 of 61
  15. 15. GSM Association Non ConfidentialOfficial Document <WG.NN>3 Ideal mobile applicationWe have already established the type of constraints that mobile applications encounter,where all critical resources (such as battery, memory and processor) have certain limits.However, key generic characteristics of functionality or use case scenarios have yet to bedefined; a topic which is addressed in subsequent sections.3.1 AsynchronyThe concept of asynchrony has already been introduced briefly in chapter 3. There are 2main aspects to asynchronous network connections: 1. Network connections should not block the main thread responsible for handling user interface and system events. 2. If network requests do not depend on each other, they should be handled in parallelAsynchronous networking would always imply separate threads; although it makes trackingof results and the state of an application non-trivial. This drawback, however, is wellunderstood and competent solutions are still provided.The architecture of applications is driven by the APIs that platform vendors provide. To agreat extent, the quality of most application implementations is dependant on the platformvendor’s level of generic API support and optimization at a platform level. For example,creating separate threads and managing them effectively should already be part of theunderlying features of a target platform to allow the developer to save time and effort in notreinventing the wheel.In this context the ideal APIs should have the following features:  Creation and management of the network connections can be done from the main thread; however, the calls can lead to separate threads that are managed by framework transparent to user  All changes of states, received data, errors and timeouts are event driven  The connection can be cancelled at any time  The design of APIs allows the simple management of several connections at the same time.Developers are recommended to establish connections within a single connectivity sessionwhenever it is possible to avoid loosing dedicated channel state, which is described inSection 2.3. This would reduce network signalling and depending on the communicationpattern there can be a significant impact on a device’s battery life.3.2 Connection loss and error handlingMonitoring connectivity status and error handling are extremely important as mobilenetworks are by definition unreliable.Most platforms provide information on current connections. It is essential to check if thedevice is connected at all (e.g. not out of network coverage). Sometimes it becomesnecessary to identify the type of connection: cellular mobile network or, for example, Wi-Fi.Although the actual bandwidth can not be predicted precisely (as it depends on manyfactors, like signal strength, current network load, etc.), developers may assume that:  Wi-Fi networks are generally faster than cellular mobile networks  Traffic over Wi-Fi is relatively cheaper in comparison, or can be absolutely freePrior to commencing any network connectivity, it is worth checking if the device isconnected at all, and if it is important, check what is the type of the current connection. If the<V0.1> Page 15 of 61
  16. 16. GSM Association Non ConfidentialOfficial Document <WG.NN>device is not connected, then the application can switch to offline mode and let the userwork with cached data only. This would avoid handling inevitable network exceptions andnotifications for each network error; the overall user experience can be much smoother ifthe user can avoid constant error messages. However, if the application switches into offlinemode, it would be good to monitor the device connectivity status and as soon as the devicegets connected, the application can switch back into online mode. If there is any data tosynchronize between the server and client, the synchronization can be initiated at that pointRequest typesWhen establishing the connection, different approaches can be used to display the activityto users and determine how to handle network problems should they happen. Networkrequests can be identified as user initiated if it is going to deliver the main information thatuser had requested. User initiated network requests can also be considered as primary.Non-user initiated requests are those that are created by scheduled activities or triggered bya change in a system state, such as geo-location tracking and sending usage statistics to aserver.Secondary requests usually occur from the result of the primary request and do not bringany critical information to the user. Examples of secondary requests could be thumbnails ina friends list (list of names is critical), stylesheets or images in web page.CancellationIdeally, the user should see the progress or an indication of the primary request’s progress.It is also sensible to make the primary request cancellable, but it depends on the nature ofthe content and how it is displayed in the user interface.As a general rule if it is possible to perform any other operations on the same UI screen, it isa good practice to ensure ‘cancel’ is available as an option to terminate the request.A good example when cancellation improves usability is the web browser, which is justanother network-enabled application. A user can load different web pages on the samescreen, so if loading of one page takes too long or there was a mistake in entering theaddress, the user can always cancel the request and open different web site.When the primary request is cancelled then subsequently all secondary requests should beautomatically cancelled as well.Error handlingMobile applications should always be prepared for handling situations when networkrequests fail. Most probably any secondary requests can fail without a major impact on theuser experience. Sometimes it is appropriate to indicate subtly in the UI that information forsecondary request can not be delivered, such as broken image placeholders in webbrowsers or silhouette images in a contact list.When a primary request fails, it means that the main functionality can not be completed andthis is where error handling becomes important for the user experience.As proposed earlier, it makes sense to distinguish between a user initiated request andnon-user initiated (scheduled). If the request was user initiated and the information isexpected to be delivered as soon as possible (lets say within 1 minute), then errornotification can be done in a modal error notification with options ‘Retry’ or ‘Retry later’ ifappropriate.If a request is supposed to take longer time, and the user expects it to be guaranteeddelivery at any time later, for example, downloading music, downloading an electronic bookor a digital issue of a magazine, then in case of network failure, the application canautomatically try to reestablish the connection and if 3-5 attempts have failed, then therequest can be suspended (but not cancelled) with an option for manual resume later. It is<V0.1> Page 16 of 61
  17. 17. GSM Association Non ConfidentialOfficial Document <WG.NN>also important to not lose any downloaded data and to be able to resume the downloadfrom the place where it has stopped rather than starting from scratch.Retry mechanisms can vary and depend on importance and volume of downloaded data.Possible solutions can be: 1. Simple counting of failed attempts since the connection was first established (often the easiest solution). 2. The number of failed attempts within a certain period of time. For example, if the connection is lost more then 5 times within the last hour, then the request can be suspended. This can be a more reliable technique to avoid short but regular network problems, for instance, when a device is moving away from one network cell to another the connection can be lost when it switches between cells, but when the cell is providing good coverage, the request can be processed successfullyIf the request is not user initiated then error notification can be either non-modal with a retryoption or not shown at all. But, if the request is scheduled and repetitive, then it would makesense to change the interval dynamically to avoid reestablishing connections too frequentlyduring network loss over a long period of time. Recommended retry intervals are 1 minute,then 5 minutes and then 15 minutes. More frequent retries will drain the battery very quickly.Resuming large downloadsThe HTTP protocol supports requesting parts of files that can be used for resumingdownloads. If the server supports it and the content can be returned split (i.e. content is notdynamic), then the server may include HTTP Header as described in sections 14.5 and 3.12of RFC2616: Accept‐Ranges: bytes  Having this indicated, the client can send subsequent requests for part of the file specifyingrange what shall be downloaded, for example, to download first 500 bytes: Range: bytes=0‐499  Or for segment starting from 9500th byte: Range: bytes=9500‐  An HTTP response with partial content should have HTTP Status 206 (Partial Content) if therequested range is correct, otherwise, there will be status 416 (Requested range notsatisfiable). See Section 14.35 of RFC2616 for more details.Section 3.3 below describes how the verification of cached version can be done in HTTPusing ETag; and it is also possible to retrieve partial content with preceding verification ofthe content version by HTTP request header If-Range, as specified in Section 14.27 ofRFC2616. The idea is that the value of header If-Range should contain ETag value and thesame request should also have a Range header specifying what part of content is to be<V0.1> Page 17 of 61
  18. 18. GSM Association Non ConfidentialOfficial Document <WG.NN>received if ETag is valid. If server verifies ETag, then the partial content should be returned,otherwise, the full version of the updated content will be sent.Though the client can also use Range header with conditional headers such as If-Unmodified-Since or If-Match, if the condition fails then client should handle the HTTPstatus code and a new request for retrieving the updated content. If-Range header can helpto do this in a single request using either ETag or last modified date.Support for resuming downloads is extremely important for large content transfers on mobiledevices, especially with the growing number of tablet devices, where quality of content isrelatively high for a big display size. For instance, a single issue of a digital magazine canbe 200-400 Mb and it would be incorrect to redownload the whole file if the network failsafter downloading several hundreds megabytes of data.The following summarises the topics discussed thus far: 1. Check connection availability. 2. In offline mode use cached data. a. For any outgoing request that includes user-entered data the data should be saved locally and an attempt made to deliver to the server. b. If it fails to deliver the request, then the user should be asked if the request shall be retried or retried later (with permanent saving in case the application is terminated). 3. If the primary request is done in online mode, then it should be displayed with a progress indicator and if it fails then the user should be notified a. If the primary request is supposed to take more than 1 minute and the user expects to get the result however long it takes (download application, song, new magazine issue, e-book, etc), then automatic retry should be implemented. b. If several consecutive retries have failed, then manual retry can be implemented c. It is good to indicate the progress of secondary requests, however, failure of them is not important and can be displayed only as a special placeholder (broken image placeholder for instance). d. If the request is user initiated then error notification can be modal. e. For repetitive scheduled requests, the retry interval should be dynamically increasing during long periods of network loss.3.3 CachingThe main idea of any caching is using more effective means of storage or transfer in orderto decrease the amount of data stored or transferred via slower channels. For networkapplications and especially in mobile networks, the cache becomes an essential part.However, there are a few common challenges relating to the overall reliability of the solutionand ensuring the delivery of up-to-date information to the user.<V0.1> Page 18 of 61
  19. 19. GSM Association Non ConfidentialOfficial Document <WG.NN> Client Network Server 1 2 3 Local cache Server cache Server Figure 9 – CachingAlthough the entire client/server solution may contain many different levels of cache,generally two categories are supported: local cache and server cache. Local cache is usedto minimize the number of network requests and increase the speed of displaying results.The server cache works together with the local cache in order to decrease the amount ofdata transferred via the network, whilst ensuring that the user gets the latest version of theinformation.The diagram above shows the journey of a regular request from a mobile client to a webserver: 1. On the first stage the client checks if the requested content is stored in local cache and if it is still valid. If the content is valid, then the data goes back to the user immediately without sending any requests to the network. 2. If the local cache contains data but needs validation, then the client includes a version or checksum or the last modified date of the content that client already has. If server can not find any newer version of the content, it notifies client that the local version can be used without sending the whole file over the network. 3. If there is no local version of the file, or the data is not up-to-date, then the server sends the latest version over the network. With proprietary implementations (depends on the nature of the requested data), it might be possible to send only changes to the local version.When an application is being designed, it is worth defining what types of content are goingto be used and specify the caching strategy accordingly:  Content can be cached without further validation. For example, if content has a unique identifier and can not be modified on server side, such as static photos in user albums (usually new photos can be added or old photos deleted, but not modified).  Content can be cached locally, but needs validation with the server. A good example is the user’s profile or profile picture which usually does not change very often but occasionally may be updated.  Content can not be cached at all. Examples: audio streaming, chat, etcDepending on the privacy of the content and security of local storage, some cacheablecontent shall not be kept on device.Local caches face the following problems:  Size limitations – Device storage is always limited and depending on the application or the data, the cache should be limited to the corresponding size. Sometimes, it may worth giving user an option to define cache size.<V0.1> Page 19 of 61
  20. 20. GSM Association Non ConfidentialOfficial Document <WG.NN>  Invalidation of content – Usually web content has expiration date that can be defined by server; however, it also can be defined manually depending on the nature of the data.  Prioritisation of content – As the storage is limited and eventually cache will be filled to its limit, new entries in the cache should replace old ones with the lower priority. The cache storage may have different strategies for this – removing the least frequent used, the oldest or the biggest entries.With HTTP version 1.1 the cache control became part of the standard and is well describedin section 14.9 of RFC2616, which sets out the options for defining if content can becached, the expiry date and the versioning of the content.The HTTP protocol defines a mechanism for checking if the client’s cache has the sameversion as the server. If the server recognises that the client has the up-to-date version ofthe requested data, then the response will consist only of HTTP headers and the wholecontent is not sent which can considerably reduce the network traffic.The general idea is that on the first request the server sends a response with an additionalheader that can indicate the version of the content. The second request already comes fromthe client with information about the version to the server and if the server does not haveany updates to it, it replies with HTTP Status Code 304 (Not Modified), or, otherwise, itsends the full content with the new version indication.The version can be indicated simply by the last modified date in the Last-Modified HTTPresponse header (See Section 14.29 of RFC2616 for more details). The consequentrequest should come with HTTP request header “If-Modified-Since”, as defined in Section14.25 of RFC2616 or “If-Unmodified-Since”, as defined in Section 14.28 of RFC2616.ExampleFirst request: GET /image.png HTTP/1.1 Host: Connection: keep‐alive  First response: HTTP/1.1 200 OK Cache‐Control: max‐age=31536000 Content‐Type: image/png Date: Mon, 21 Feb 2011 12:41:47 GMT Expires: Tue, 21 Feb 2012 12:41:47 GMT ETag: "11f‐49bc3eabc9c80" Last‐Modified: Tue, 08 Feb 2011 11:47:46 GMT Content‐Length: 28702 Connection: Keep‐Alive  <V0.1> Page 20 of 61
  21. 21. GSM Association Non ConfidentialOfficial Document <WG.NN>Consequent request: GET /image.png HTTP/1.1 Host: If‐Modified‐Since: Tue, 08 Feb 2011 11:47:46 GMT Connection: keep‐alive  Response: HTTP/1.1 304 Not Modified Date: Mon, 21 Feb 2011 12:44:07 GMT  This example shows that consequent requests can produce huge savings, in this case itresponded only with short headers that are less than 1KB rather than 28KB of actualcontent, and it also gives reliability in delivering up-to-date content, so if the server hadmore recent copy of the picture, then, instead of 304 HTTP status, it would reply with 200status and the full content.Content can also be marked with ETag (entity tag) (see Section 3.11 of RFC2616) and theymust be unique across all versions of all entities associated with a particular resource.When ETag is received from the server, then the client can use HTTP request headers:  “If-Match” [RFC2616 section 14.24] – to deliver only the version that is requested, otherwise HTTP Status Code 412 (Precondition Failed) is returned  “If-None-Match” [RFC2616 section 14.26] – to deliver only if the server has any other versions other than the client has, otherwise HTTP Status Code 304 (Not Modified)  And “If-Range” [RFC section 14.27] – to deliver part of file (using Range header) only if ETag matches, otherwise the whole file is delivered.Taking the same example, it can be seen that the first response also includes ETag, so theconsequent requests either contain either only one condition or both conditions for ETagand last modified date, for example:ExampleConsequent request: GET /image.png HTTP/1.1 Host: If‐None‐Match: "11f‐49bc3eabc9c80" Connection: keep‐alive  <V0.1> Page 21 of 61
  22. 22. GSM Association Non ConfidentialOfficial Document <WG.NN>Response: HTTP/1.1 304 Not Modified Date: Mon, 21 Feb 2011 12:44:07 GMT  3.4 SecurityAlthough many aspects of security apply to both mobile applications and mobile platforms,this section is meant to bring to attention aspects of Network Security, covering secure dataexchange between mobile device and cloud web services. The key aspects are mainly:  Classification of information  Authentication of users on Web Services  Secure data exchangeThe following aspects of security have to be always taken into consideration by solutiondesigners, but they are out of the scope of this document:  Device Security o Aspects of device access security, such as device unlock and remote wipe of storage in case of device loss  Content protection o Access control to users personal data including Personal Contact Information, Address Book, Call History, SMS Messages, Mobile Wallets, Current Location, Passwords, VPN keys, etc.  Encryption of locally stored data o Protection against attacks o Considering Internal and External factors, damage caused by malicious software and virusesClassification of informationWhen designing network enabled applications, it is important to understand user concernsin regards to the data the user consumes or shares with the cloud. In a simplistic way thedata is classified as:  Public – information which is freely available in the Internet, can be found by other users and cannot be associated with a particular user.  Private – the data which can be somehow associated with the user, leading to compromised security.Below is the list of some examples supporting the above definitions:  Use case #1: Application provides read-only access to the information which can be easily found in the internet by other users. Classification: Public  Use case #2: Application presents the same information as in Use Case #1, but some feedback is collected and stored in the cloud. This can be customer preferences, history of articles viewed, user comments or rating of the content. Classification: Private – as data associated with the user can be potentially used against him. The same data can be classified as Public in case it is anonymized –<V0.1> Page 22 of 61
  23. 23. GSM Association Non ConfidentialOfficial Document <WG.NN> this however, must be made clear to the user. User consent is required in both cases.  Use case #3: Productivity application, such as "TODO list", synchronizes data to the cloud. Classification: Private – user could store sensitive information in the application, such as holiday dates, which can potentially indicate presence of user in his home. User consent is required  Use case #4: Messaging application; Social networking application Classification: Private – user can exchange sensitive information which could potentially compromise his security. User consent is required in this caseWhen the data flow and sensitivity of transferred information is understood it is a good timeto estimate the impact on the user in case of establishing monitoring ("Sniffing") of suchtraffic by an unauthorized party. Sniffing of user traffic may occur on Internet connectionsprovided by public Wi-Fi access points, those provided by small businesses, or can evenhappen in unregulated corporate environments. It may take seconds for an intruder tointercept the Authentication token of application’s communication channel and impersonatethe user. A number of examples of such intrusions can be found on YouTube, such asimpersonation of social networking users.AuthenticationAccess to any Private data must be put under control and this is normally achieved byauthenticating the client. The most basic authentication is achieved by validation of a pre-registered client ID with a password. Although client ID is most frequently just a personalemail address of the user, device ID can also represent a client.It is important to differentiate Device Authentication from Device Identification, where thelatter does not require validation of account with password and often used just to tracecustomers. Solutions relying on Device Identification pose security threat if involved withhandling Private data, as transfer of device to a different person if lost, stolen or sold, willautomatically provide access to the data of the previous user.Never use static device IDs such as Device Serial Number, Telephone Number or IMEI inclear form, use either obscured device IDs (can be hash code based on the listed IDs) orautomatically provisioned Unique Identifiers (UID).User authentication can also be implemented by integration into Third-party Authenticationproviders, such as Google ID, FaceBook ID or Microsoft Passport. For this reason refer toAPIs provided by these vendors or adopt open protocol OAuth ( must be performed every time the application establishes a new session.Whichever approach is used for this purpose, it is important to ensure that:  Authentication is performed using secure authentication protocols – HTTP Basic authentication is not enough, HTTP digest would be more appropriate; however in some cases, even stronger methods are required  Proprietary implemented authentication, must be performed over secure SSL/TLS based communication channel  When a session is established, user or device credentials are not exchanged over an unsecured connection, so that Session IDs, Application PINs, Service Passwords, etc. are never exposed as these will provide an open door for intruders.Strong AuthenticationFor stronger authentication implement Multi-factor authentication which involvescombination of 2 or more stages of authentication. Variety of approaches exists and as anexample can be a combination of User and Server authentication, where verification of the<V0.1> Page 23 of 61
  24. 24. GSM Association Non ConfidentialOfficial Document <WG.NN>server is performed by client using additional security certificates. This type ofauthentication is used by businesses for implementation of Virtual Private Networks (VPNs).Secure data exchangeImplementation of secure communication using HTTP over SSL/TLS protocols (HTTPS)within the applications is not always favoured due to required additional effort; although,sometimes client applications would be the less affected. Indeed, extra effort is needed forimplementation of secure solutions, however the investments you will put into security ofyour product will be highly regarded by customers. In many cases, the additional effort maybe only needed to purchase and install a trusted certificate on the server and update theclient to use HTTPS instead of HTTP.Encryption/decryption of traffic may have an impact on user experience, as additionalprocessing time at both ends contributes to higher latency. This also has an impact onbattery life. On high-end devices, such as iPhone, these drawbacks are addressed byhardware accelerated encryption, which maximizes application performance.Input ValidationFollowing general guidance that any input to the application should be validated, it becomeseven more important with network applications, as the data can always be damaged, ordeliberately crafted input to cause damage in your software.The consequences of invalidated user input can be either crashes of the application or evenrunning malicious software which can destroy sensitive data or even steal private data byexploiting breaches such as buffer overflow, format string vulnerabilities, stack overflow orrace conditions.Although, many programming languages check input in standard APIs to prevent bufferoverflows, native languages such as C, C++ and Objective C put this responsibility ondeveloper. Even though, managed languages do try to prevent it, they still may be linked tonative C libraries, and sometimes, open-source libraries that are not protected from defectsand potential security problems.Ideal platformSuch a platform would:  Support seamless secure user and server authentication  Provide secure transport by default  Provide secure storage for credentials3.5 Efficient traffic usage3.5.1 Cloud-based transformations,There is a category of mobile network applications that use data from public resources suchas news web sites. However, using public resources which are not under the developer’scontrol poses several risks as it fails to exploit standardized APIs, and is often inefficient: 1. The format of data (HTML code) can be changed at any time which may cause application failure on the customer’s device. 2. The amount of data that is needed for the application might be significantly more than is necessary increasing network traffic and latency.In this case, it is highly recommended to check if there are any APIs (Web Services)provided from this resource that are standardized, less likely to be changed and containless unnecessary mark up information. If no APIs are available, then the developer can alsoconsider creating their own Web Service in order to have full control over the protocol anddata being transferred between device and server. In this case, even if the website changes<V0.1> Page 24 of 61
  25. 25. GSM Association Non ConfidentialOfficial Document <WG.NN>its HTML code, then only the Web Service should be updated with the client remainingunchanged.As the development of a server and Web Service might be out of the developer’s skill set,some existing third party tools can be used for this. A good example is Yahoo Pipes( which provides a graphical user interface to aggregate, manipulateand mash up content from different sources around the web. Results can be delivered asRSS or JSON.A few examples of types of operations can be done with Yahoo Pipes: 1. Fetch data from different sources like feeds, web page, Google or Yahoo search, Flickr photos 2. Custom input data can be used as an external parameter. For example, it can be a search query 3. String manipulations such as regular expressions, text analyser, translation, etc 4. Location builder from a string 5. Mathematical operations 6. Filtering and sorting of the resultThe picture below shows an example Yahoo Pipe that aggregates the results of search from4 different sources, sorts the items by date and filters out non-unique titles and compiles aresult of maximum 40 news stories. It would even have been possible to combine the feedsof different languages and automatically translate them before aggregation. Figure 10 – Yahoo Pipes solution3.5.2 Media TranscodingIf the inefficiency in text based data formats can be improved by compression, the case formedia formats – pictures, audio and video – is somewhat more complex as the quality of themedia has a huge impact on its size. Therefore special care should be taken whentransferring media.<V0.1> Page 25 of 61
  26. 26. GSM Association Non ConfidentialOfficial Document <WG.NN>Most mobile phones have fairly low (i.e. few-megapixel) cameras; however, if an applicationuploads a picture taken by this camera for a social-network website, which will reduce thesize of any picture, there is no point in sending the original quality. The difference in sizecan be around 30-50 times, which also makes the same difference in time that takes toupload the picture.The same applies for downloading pictures to a mobile application. If the picture issupposed to be displayed only on the mobile display, then there is no point in downloadingthe original size. This is always applicable, for example, for thumbnails, however, for full-screen photos some additional overhead might be allowed to allow users scaling up theimage.The size of video files can be enormous if a smartphone has an HD camera; in this case itmight not be possible to upload a video over the cellular network without transcoding to alower quality file.If an application has video playback functionality, then a few points should be taken intoaccount: 1. It is better to not exceed resolution of the display where the video is going to be played(mobile device display or external display) 2. If the video should be played in real time, then the bandwidth of current network shall be checked to identify the appropriate bit rate of video that can be played without constant delays. 3. Progressive download and download resuming (section 3.2) may be usedApple puts strict requirements for applications regarding online video in applications,particularly if the video exceeds either 10 minutes duration or 5 Mb of data in a five minuteperiod, you are required to use HTTP Live streaming; otherwise Progressive Download canbe used.The ideal APIs on the platform to ensure that developers can leverage media transcodingwould be: 1. Basic image resizing 2. Audio codecs that would allow quality reduction (and size) of the audio 3. Reducing video quality and resolution in order to reduce size of video media. 4. Support of media streaming protocols such as HTTP Live Streaming or RTSP3.6 CompressionThe HTTP protocol defines mechanism of transferring data in compressed ways, if theserver can support it. Statistically, most servers do support it and, usually, enablingcompression is a very simple task for the most popular web servers.Compression can be very effective for text data by reducing overall on average by 80%. Forbinary content, like photos or videos, however, compression does not give much effect.The main idea of the HTTP compression is that if the client supports any of the standardcompression methods such as GZip, Deflate (zlib) or LZW, then it mentions it in the requestto the server and then if the server supports the listed methods it can send a compressedresponse.The indication that the client supports compressions is sent via HTTP HeaderAccept-Encoding.<V0.1> Page 26 of 61
  27. 27. GSM Association Non ConfidentialOfficial Document <WG.NN>Example request indicating that client supports GZip and Deflate compression methods: GET  /  HTTP/1.1 Accept‐Encoding:  gzip,  deflate Host: Example response indicating that content is compressed: HTTP/1.1 200 OK Content‐Length: 438 Content‐Type: text/html; charset=UTF‐8 Content‐Encoding: gzip … …  RFC2616 section 14.3 and section 3.9 explains Accept-Encoding header in more details,and particularly, what can be useful is defining priorities (importance) of using differentmethods. HTTP compression technique includes negotiation, to make sure that both theclient and server support the same compression methods. Therefore, apart from standardcompression methods, clients and servers can even implement more efficient compressionfor certain types of content.In order to simplify usage of compression for developers, the ideal API for HTTP clientwould support the main compression methods GZip, Deflate (zlib) and compress (LZW) withthe corresponding Accept-Encoding header added by default and the contentdecompressed by default. However, developers would also be able to disable it or redefinehandling of compression in order to support custom compression methods.ReferencesRequest compression Web delivery with HTTP compression Background / Foreground modesMost mobile platforms support some distinction between background and foreground modesfor applications. The precise distinction varies from platform to platform but typically anapplication is said to be in the background if no part of its UI is visible and the user is unableto interact with it.Given that a user is unable to interact with an application that is in background mode,careful consideration should be given to this aspect of its design to ensure that unnecessarywork is not carried out whilst in this mode. Ensuring that the application minimizes itsresource footprint whilst in background mode will generally help to improve the userexperience of the foreground application.<V0.1> Page 27 of 61
  28. 28. GSM Association Non ConfidentialOfficial Document <WG.NN>More specifically the application will receive some indication from the platform when atransition between modes occurs and should take advantage of this to gracefully release (orotherwise disable) the following application components  Handlers  Timers  Network transactions  Memory/Objects  Media codecs  File & databasesSpecial attention should be given to applications that interact with the network on a regularbasis as this drains the battery and generates signalling traffic. In most cases applicationsshould not need to interact with the network whilst in background mode (given that there isno way to present results, unless it uses notifications system) and so network activity shouldbe prevented when the application is in this state. Idle screen widgets (e.g. weather / newswidgets) are common culprits here; however, it does not apply for applications such asinstant messengers, as they need to be connected all the time.However there can be no hard and fast rules in this area – for instance a music player islikely to want to continue to decode audio even when in background mode. But at the veryleast the developer should review the detailed operation of the application in each state toensure its resource footprint is appropriate.Similarly applications that do need to interact with the network whilst in background modeshould consider alternative approaches. For example it may be possible to aggregate thetransactions of several applications so that the background application can “piggy-back” itstransactions onto those of others. A common reason for background applications to accessthe network is to poll a server, however a better approach is to use push notification(if supported).The HTTP “Keep-Alive” mechanism is frequently used as the basis for push notificationsystems however this only works well if there is a centralized client side component forreceiving/routing notifications (i.e. as part of the platform e.g. Android C2DM).In case push notifications are not available or not suitable of some reason, keep-alive connections can be usedinstead to replicate push notification mechanism and avoid frequent polling of data. The main advantage ofkeep-alive over polling is that connection can be kept without frequent transfer of data and therefore, thecellular state can be switched to lower power; however, if there is anything to be delivered from server, it canbe done immediately. It would also necessary to make sure that connection is still alive by sending non-frequent data packets (minimum 10 minutes, but apple recommends ~26 minutes).Some platforms provide a richer (more fine grained) application lifecycle than others.Developers should exploit the lifecycle to its fullest to achieve the best user experience.For example it may be desirable to retain a group of thumbnails across several applicationstates that represent the “active” cycle of the application (where “active” might encompassbackground as well as foreground modes) but release them across states that represent aless active cycle. Failing to consider the target lifecycle can result in applications thatperform well on one platform having poor performance when ported to another.Applications should also consider altering their resource footprint in response to changes indevice state. In some cases changes in device state may fall within the scope of theapplication lifecycle (e.g. an incoming phone call is likely to result in the application makinga transition to background mode), however other changes in device state may lead to adifferent form of notification (applications may need to register to receive screen lock eventnotifications for instance). A useful approach is to treat each device state transition as aseparate use-case and identify those uses-cases that impact on the application. Using this<V0.1> Page 28 of 61
  29. 29. GSM Association Non ConfidentialOfficial Document <WG.NN>approach would (for instance) show that in the case of the music player mentioned earlier itmight be worth shutting down the audio decoder task when the speaker is muted.3.8 Application ScalingWhen designing a mobile application it is important to design it so that network activity is notconcentrated at specific times and is tolerant of geographical loading problems:  Handsets are frequently synchronised to a standard clock source so frequent updates using exact times may cause short overloads to the application servers and the radio network  The network capacity of a local area will be significantly lower than the product of the number of handsets and their assigned bandwidth. On occasions there may be large numbers of users in a specific location<V0.1> Page 29 of 61
  30. 30. GSM Association Non ConfidentialOfficial Document <WG.NN>4 Detailed RecommendationsIn previous chapters theoretical foundations of the developer’s guidelines have beendescribed and relevant principles explained in some detail. In the following, those principlesare mapped to limitations of each target platform (iOS, Android and Windows Phone 7).4.1 iOS4.1.1 AsynchronyAn application’s main thread is responsible for all activities including handing of the systemmessages, input events, etc. iOS makes sure that the main thread is always alive by amechanism called WatchDog which can terminate the process if it does not respond withincertain time (approximately 20 seconds). Therefore, if any synchronous operations arecalled, the developer needs to be sure that these operations can be finished as fast aspossible. This becomes very critical for networking and especially in the mobile networkenvironment, as network timeouts are much longer than the watchdog’s. For example,Domain Name Resolution will be timed out after 30 seconds of not having any responsefrom the network.The design of iOS APIs is done to simplify development as much as possible, and in mostcases developers do not even need to think about creating separate threads, as everythingis done transparently and asynchronously. However, some of the methods hidesynchronous networking which should be used very carefully and only in separate threads.Apple provided a list of such methods in WWDC’10 which is:  Utility methods: ‐initWithContentsOfUrl:  +stringWithContentsOfURL:   DNS: gethostbyname  gethostbyaddr  NSHost (Mac OS X) +sendSynchronousRequest:returningResponse:error: As it was explained before, network asynchrony is not just calling network functions from themain thread to not block UI, but also handling requests and responses independently fromeach other. This can be done by using requests queues and, although standard iOS SDKdoes not provide this functionality, there are a few third party libraries that provideimplementations of request queues.“Three20” library wraps Foundation’s classes such as NSURLRequest, NSURLConnection toadd an extra functionality, for example, more advanced caching, queues and retrymechanism. The advantage of using the “Three20” network module can be significant if thenetwork activities are integrated with any other “Three20” modules, especially with its userinterface.Another library that gives rich network functionality is ASIHTTPRequest. Unlike “Three20”,this library wraps lower level C API – CFNetwork, however, it is an Objective C library.Some developers may even prefer ASIHTTPRequest rather than standard Foundation API,as it implements many additional features such as:  Requests queue  Simple API for sending POST requests with files attached and post values<V0.1> Page 30 of 61
  31. 31. GSM Association Non ConfidentialOfficial Document <WG.NN>  Tracking progress of a single request or the whole queue with automatic update of UIProgressView  gzip compressed request bodies  Resuming interrupted downloads Section 3.2  Background-mode requests  Client certificates support Section 3.4  Automatic support of network indicator  Automatic retry  Persistent connections – to reuse single HTTP connections for a several small requestsReferencesASIHTTPRequest documentation Connection loss and error handlingArchitecturally, it would be better to apply the MVC pattern to separate data handling fromthe user interface and the main application logic, where the Model would be the best placeto isolate data loading, error handling and connection loss, and the use of other datasource such as local database or local cache if required.As described in Section 3.2, it is good idea to make the application aware of the currentnetwork status and if no network is connected, then the application can immediately switchto offline mode avoiding network errors.Apple provides sample code in project “Reachability” (see reference below) which can beused for detecting network status and notifying about any changes. Generally, the methodreachabilityForInternetConnection would be appropriate for most of the cases.If the application detected that there is no internet connection and offline mode should beused, then local data shall be used. The simplest solution without building a local databasewould be to use standard NSURLRequest, but with custom cache storage that supports on-disk cache (as described in Section 4.1.3) and cache policy parameter set toNSURLRequestReturnCacheDataDontLoad. This will avoid attempts to establish a networkconnection that is going to fail, and will return the result immediately, if anything has beencached. The rest of application can be left unchanged with error handling as if it was usingthe network.For any network request that uploads data to a server regardless of size, for instance,uploading picture, or even updating status on a social network, it is advisable to use TaskCompletion API to make sure that content can be delivered even if the user minimizes theapplication. Subsequently, it is also important to make sure that entered content is not lostin case of the network failure and can be retried without need to reenter the data (or retakethe picture.Long downloads, such as, music files, digital issues of magazines or any other large files,shall be resumeable and if the server and the content support HTTP partial download, thenthe request for restoring download from any part of the file can be initiated by adding HTTPRange header: <V0.1> Page 31 of 61
  32. 32. GSM Association Non ConfidentialOfficial Document <WG.NN>// Requests part of file starting from 1024th byte [URLRequest setValue: @"bytes=1024‐" forHTTPHeaderField: @"Range"];  ReferencesReachability reachability CachingThe Foundation framework provides simple to use cache management, giving developerscontrol over what can be cached and where. Standard NSURLCache is very limited and,although, the full MacOS X version supports both on-disk and on-memory caches, but theiOS version can store only in memory. Furthermore, by default the capacity of memorycache gets set to zero, meaning that even memory cache will not work if it is not enabledexplicitly.A simple test shows that memory capacity is set to zero by WebView (even if it is not usedin the UI) from a separate thread. To make the matters worse, it is also not documented atwhat point this happens – perhaps as a result of a bug or a hidden feature. Therefore asimple and reliable workarounds would be to subclass NSURLCache and redefine methodsetMemoryCapacity which will ignore all calls with value 0 and will pass through all othervalues to the original method.Example: ‐(void)setMemoryCapacity:(NSUInteger)memoryCapacity {     if (memoryCapacity == 0) {         return;     }      [super setMemoryCapacity:memoryCapacity]; } The standard class NSURLRequest includes a parameter cachePolicy which can retrievethe following values: NSURLRequestUseProtocolCachePolicy – the default cache policy for the protocol that is being used for the particular URL request. Suitable for most of the cases in online mode. NSURLRequestRelaodIgnoringCacheData – ignores any local cache and will try to load data from the originating source. Suitable for online mode and for certain use cases, when data should not be cached, for example, for keep-alive connections. NSURLRequestReturnCacheDataElseLoad – returns data from cache even if it is expired. If there is no cached version, then it will try to download the data from the originating source. Suitable for certain types of content such as static photos.<V0.1> Page 32 of 61
  33. 33. GSM Association Non ConfidentialOfficial Document <WG.NN> NSURLRequestReturnCacheDataDontLoad – returns data only if has been stored in local cache and does not attempt to retrieve it from the origination source if there is no cached version. Suitable for offline mode.Example: // Creating URL request NSURLRequest  *theRequest  =  [NSURLRequest  requestWithUrl:     [NSURL URLWithString:@””]     cachePolicy:NSUrlRequestUseProtocolCachePolicy     timeoutInterval:60.0];  // Initiation the connection with the request NSURLConnection  *theConnection  =  [[NSURLConnection  alloc]     initWithRequest:theRequest delegate:self];  if (theConnection) {     // Prepare for receiving the data } else {     // Handle the error }  The framework also allows the response to be altered before it gets stored into local cacheby implementing connection:willCacheResponse:. Usually, this method is used to avoidcaching of some private date, and some implementations do not cache any traffic that goesthrough encrypted protocols such as HTTPS.If in-memory cached is used, it would be reasonable to clean up the cached data if theapplication receives a memory warning.Currently, the standard NSURLCache does not support all features of HTTP cache such asconditional HTTP request headers, for instance, “If-None-Match”, “If-Modified-Since”, thathas been described in Section 3.3.Although, the default NSURLCache is very limited and can not help much for implementingoffline mode, the API still gives a solid framework that can be used for simple integration ofthe developer’s own implementation of cache or own subclass of NSURLCache class.There are a few implementations of custom cache classes:  “Three20” framework (see reference below), that has been developed for the facebook application, gives also choice of type of cache storage such as Memory, Disk or Network and provides separate in-memory storage specifically for images to optimize performance. However, their cache is not subclass of NSURLCache and requires using their request classes as well  SDURLCache – subclass of NSURLCache with on-disk cache support.Cache in web applicationsYahoo! did a research how mobile Safari works in iPhone regarding caching and some keyfacts can be used for architecting and implementing web applications:<V0.1> Page 33 of 61
  34. 34. GSM Association Non ConfidentialOfficial Document <WG.NN> order to be cached by Safari, the HTTP content should include either “Expires” or“Cache-Control” header. Expires: <Expiration time in GMT Format> Cache‐Control: max‐age = <Expiration time in seconds>  The browser’s cache applies a limit to the cacheable content, which should not be largerthan 25 KB (or 15 KB according to the latest tests) of uncompressed data. Even if it istransferred using HTTP compression, the browser will still uncompress it before trying to putit into cache. This means, that the correct distribution of content over small files and theminimisation of each file, particularly, JavaScript, CSS and HTML, becomes highlyimportant for the performance of mobile web applications.ReferencesThree20 Framework class Loading System Programming Guide SecurityAlthough the iOS operating system is based on Mac OS X and most of the security hasbeen inherited from there, because of the differences in the usage, there are somediscrepancies in the APIs and security models.iOS security is based on three main services in the Core Services layer, which are:  Keychain Services – secure storage of passwords, keys, certificates and other secrets.  Certificate, Key and Trust Services – creating and managing certificates, creating encryption keys, encryption and decryption of data, signing and verification of digital signatures.  Randomization Services – cryptographically secure pseudorandom numbers.On a higher level, CFNetwork and subsequently URL Loading System use these services,for instance for providing secure transport protocols and supporting SSL and HTTPSconnections.<V0.1> Page 34 of 61
  35. 35. GSM Association Non ConfidentialOfficial Document <WG.NN> Figure 11 – CFNetwork Component DiagramKeychain Services has major difference from the Mac OS X version. In Mac OS X, keychainsecurely saves passwords and if an application requests information from there, then user isasked to give permission by entering his password. In iOS the device is already secured byPIN number, and, therefore, user is not asked to enter any passwords or confirmations,however, keychain allows accessing the data only by signed applications, and eachapplication has individual storage and can not access information from any otherapplications.As mentioned earlier, URL Loading System supports the HTTPS protocol by default, sodevelopers do not need to put any extra effort in establishing a secure connection with theserver (if the server also supports HTTPS).Apple has also done great job in supporting developers to develop secure software anddevelopers are highly recommended to familiarise with documents from Apple DeveloperNetwork:  Secure Coding Guide. The document covers all aspects of security and not only network security. Explains in details topics such as Buffer Overflow, Stack Overflow, Input Validation, how these can be used by attackers to run malicious code and how this can be avoided. The design of secure user interface is also touched in the document which explains that security should not compromise usability of an application.  Security Overview. Gives more details about cryptography and secure APIs in iOS and Mac OS X.  Keychain Services Programming Guide. Contains section related to keychain services in iOS and gives guidance about how the relevant APIs should be used.  Certificate, Key, and Trust Services Programming Guide. Explains how the APIs for managing and using certificates and encryption/decryption of the data should be used.4.1.5 Data formatsJSONJSON is very popular these days and some web sites provide access to their APIs onlyusing JSON rather than XML.The most widely used Objective-C JSON parsers are YAJL, JSON Framework and TouchJSON (see references below). Each of these have their own advantages anddisadvantages.<V0.1> Page 35 of 61
  36. 36. GSM Association Non ConfidentialOfficial Document <WG.NN>YAJL is sequential access parser which is similar to SAX parser for XML. As it does notneed to keep all data in memory, the obvious advantages are low memory footprint andparsing speed which would be suitable for huge amounts of data or even streams of data.The Touch JSON library shows good results in speed benchmark and it has very simple touse API. For example, to parse JSON into NSDictionary object, the code looks like this: SBJSON *jsonParser = [[SBJSON new] autorelease]; NSString *jsonString = ...; return [jsonParser objectWithString:jsonString error:NULL];  It can be even simpler by using NSString extensions: NSString *jsonString = ...; return [jsonString JSONValue];  Encoding to JSON can be done by NSObject extension: NSString *jsonString = ...; NSDictionary *data = ...;  jsonString = [data JSONRepresentation];  XMLiOS SDK provides only the event-driven XML parser NSXMLParser which works in the sameway as the SAX parser, but instead of callback functions it sends messages to its delegate:  parser:didStartElement:namespaceURI:qualifiedName:attributes:   parser:foundCharacters:   parser:didEndElement:namespaceURI:qualifiedName: There is also alternative 3rd party event-driven XML parser called AQXMLParser that givesconsiderable memory savings.If the application needs a tree-based parser, despite memory consumption, it is possible touse the libxml2 library that is already included in iPhone, however, it is a pure-C interface.The other alternative might be using Objective-C Touch XML framework which is a wrapperfor the libxml2 library.ReferencesYAJL<V0.1> Page 36 of 61
  37. 37. GSM Association Non ConfidentialOfficial Document <WG.NN> Framework JSON XML CompressioniOS supports compression (gzip and deflate) by default and automatically adds“Accept-Encoding” header to all requests and then decompress the response. Thisincreases the efficiency of data traffic for most network enabled applications in theAppStore.ASIHTTPRequest library supports gzip only and “Three20” also supports gzip and deflateas it wraps the standard NSURLRequest.4.1.7 Background / Foreground modesWith version 4 iOS started supporting multitasking on almost all devices apart from iPhone2G, iPhone 3G and corresponding models of iPod Touch. However, iOS multitasking is notthe same as developers are used to on desktop operating systems. The main difference isthat iOS multitasking limits background activities due to the limited resources of thehandset, and also due to the different usage of mobile applications.iOS gives developers 7 different background services that can be implemented in theapplications:  Fast application switching - suspending application with preservation of its state and quick resume.  Push notifications - deliver information from backend to application that is not currently running in foreground.  Local notifications - scheduling of delivery of push-style notifications, while an application is suspended or closed.  Background audio - play audio content through the unified playback system on the device while application is in background.  Task completion - gives extra time to complete a task in background.  Location and navigation - tracking the location changes.  Voice over IP - make and receive calls using an internet connection .Almost all these services may involve network activities (apart from fast applicationswitching and local notifications), and extra care should be taken to not reduce batteryperformance of the user’s device and also to not overload thenetwork.Push notification is a well optimised technology compared to polling data, however, if it isnot used carefully, it can cause problems in the network, mainly, related to simultaneousbroadcast of notifications to many devices (latest news, some offers, etc).<V0.1> Page 37 of 61