What are we going to build?
In this tutorial, you’ll learn how to build a mobile application that searches Twitter via a keyword. The app can be tested in a web browser, mobile browser, or installed on your phone. The final app looks like:
Before you begin
- Tutorial level: advanced.
- Prerequisites: an Appery.io account; dev.twitter.com account with registered application (if you don’t have one, you’ll need to create it before you begin) and two keys (consumer and consumer_secret) for the application. You must also set your application Twitter settings to have read-and-write access, allow the app to sign-in with Twitter, and generate your access token and secret access token.
To create a new app go to https://apps.twitter.com/ page. Enter required information and click “Create your Twitter application” button. You will be redirected to the page with App settings where you can find consumer key
(API key) and consumer_secret key
(API secret).
To allow the app to sign-in with Twitter, go to the
Settings
tab and tick the corresponding checkbox; to change the access model to you app, switch to thePermissions
tab:
Creating a new app
Let’s start by creating a new app.
1. From the Apps
page, click “Create new app”, enter TwitterSearchApp
and click “Create”.
2. The mobile editor will be loaded; open startScreen
.
In the center of the editor, you should see the phone frame (after opening startScreen
):
3. You are now ready to build the UI with jQuery Mobile
components.
Set the Swatch
to F
on the PROPERTIES
panel to change the app’s color scheme.
To change your theme and swatch settings, you need to import the available default themes via plug-ins first:
CREATE NEW > From Plug-in
(or click “Add more Themes” fromApp settings > General
), which will open a window with the list of available themes for importing. Select the theme(s) to import and click “Import selected plug-ins”.
At the very top of the phone screen, you’ll see the “Caption” text. This is the app header. Click on the header, and change the text to TwitterSearch
in properties.
4. In PALETTE
, locate the Input
component.
5. Drag and drop it into the screen. In PROPERTIES
, clear the field Text
and set the Placeholder
to Input a keyword for search
:
6. Rename the component. It will be easier to refer to the component later when we use the Twitter Search
API. Select the Input
component, and in PROPERTIES
, change the Name
to searchInput
.
7. Next, place the Button
component below the Input
component, and change its Text
to Search Twitter
. Set the button Name
to searchButton
and Swatch
to F
:
8. This is all we need for entering a search query. You can quickly test the app in a web browser by clicking “Test” from the top menu. You can also test this on your mobile phone. First, make the app URL public in the Test
window. Then enter the URL shown, email the link to your mobile phone or scan the QR code.
9. Now you’ll add a Grid
component with other components inside for displaying the search results. Locate the Grid
component and drag and drop it below the “Search Twitter” button.
10. Since we need only 1 column, in PROPERTIES
, set Cols
to 1
and click “Apply“. Now the view should look like:
To select the Grid
component, use the breadcrumbs above the phone frame:
11. Next, change the Grid
’s Name
property to: outputGrid
.
12. Inside the grid, you’ll display 4 items:
- Twitter picture
- Twitter username
- Tweet’s time
- Tweet’s text
13. You’re going to imitate 3 cells by adding another Grid
component with 1 row to the upper cell; drag and drop a Grid
component into the upper cell of the outputGrid
and change its property to 1 row.
14. Rename the inner grid to innerGrid
.
15. To remove spaces between the cell and inner Grid borders, select “innerGrid,” and in PROPERTIES
, set all Margin
fields to 0. Select the upper cell of the outputGrid
, and set all Padding
fields to 0
.
16. Locate the Image
component in the PALETTE
, and drag and drop it inside the upper left cell in the united grid.
17. Select the image, and in PROPERTIES
, rename the component to tweetPicture
. Then change its Dimension
property to 78
by 78
. Resize the first cell to the size of the image, so it looks like:
18. Find the Label
component, and drag and drop it inside the upper right cell. Set its name in PROPERTIES
to tweetFrom
. This component will display the Twitter username. Take another Label
component, and drag and drop it inside the same cell below the tweetFrom
label. Set its name as tweetTime
. This component will display the date and time of the tweet. For a nicer view, set the tweetFrom
margin fields: top (first one) to 5
, bottom (third one) to 16
:
19. Now you’ll add a component that displays tweets. Drag and drop another Label
component into the bottom cell. Set its name to tweetText
.
20. Change the labels’ color to black (#000000
) and remove the italic style (if needed) by clicking the “I“ in PROPERTIES > Font
.
Click “TEST” again to see how the app looks in the browser.
Adding REST services
We are ready to add REST services that will connect to the Twitter
API. First, we need service settings for storing your app keys. The OAuth2
REST service will use these keys to authenticate your app in Twitter and get a special bearer key. The Search
REST service will use this bearer key for searching.
The OAuth2 REST service requires an
authorization
parameter that looks like: ‘Basic ‘ + hash, where after the word “Basic,” there needs to be a space and the hash is an encoded base64 keys combination.SearchService
requires anauthorization
parameter that looks like: ‘Bearer ‘ + bearerKey, where after the word “Bearer,” there needs to be a space, and after, it needs the bearer key from Twitter.
TwitterSearchSettings
1. From Project
view, click CREATE NEW > Service > Settings (REST settings)
.
2. For the Service Settings
name, enter: TwitterSearchSettings
. Click “Create Service”:
3. The Settings
editor will open. Add two parameters: consumerKey
and consumerKeySecret
, and replace the default values with your app keys from the Twitter developer account:
OAuth2Service
Now, create a new service.
1. From Project
view, click CREATE NEW > Service
.
2. For the service name, enter: TwitterSearch_OAuth2Service
. Click “Create Service”.
3. Enter the service URL:
1 |
https://api.twitter.com/oauth2/token |
4. For Method
, select POST. For Request Content Type
, select x-www-form-urlencoded
. For Settings
, select TwitterSearchSettings
.
5. To activate using Appery.io Proxy
, click the “New Channel” button, enter TwitterProxy
, and then click “Create”:
6. The TwitterSearch_OAuth2Service
settings should look like:
5. Open the Request
tab; we’re going to define input
parameters for the service.
6. Under Headers
, in the input
field, enter: Authorization
and click “Add”. This parameter will be sent in the request header, and will contain special (needed) authorization information.
7. For the next input
field, under Body
, enter grant_type
and click “Add”. Fill the field Value
with: client_credentials
:
8. It’s not always clear what kind of response you’ll get from the service. Test the service by going to the Test
tab.
9. You’ll need a test value: concatenate the consumer key, a colon character ‘:
’, and the consumer secret key into a single string; encode this string with a Base64 algorithm; at the beginning of the encoded string add “Basic” and a space. You can get an encoded string with an online-encoder, for instance, at http://www.base64encode.org. After filling the Authorization
field, click “Test”:
10. Save the value of access token
somewhere separately; it’ll help you later. Now you need to define the response of the service. Since you’ve just run a service test, you can automatically create the response from it. Click “Import as Response”.
11. Switch to the Response
tab to see the generated response:
12. Save.
The next step is to bind (map) the service to other elements.
Mapping the OAuth2Service
OAuth2Service doesn’t interact with UI elements. It takes the Authorization request
parameter and returns the bearer token as a response
parameter, which isn’t bound to the UI, but is needed for another service. We need to use JavaScript.
1. First, create a JavaScript module from Project
view; click CREATE NEW > JavaScript
. For the name, enter TwitterSearchJS
, and click “Create JavaScript”:
2. It’s possible to write a JavaScript function for creating an Authorization request
parameter and store the bearer key from the response into a global variable, but it is better to use a global object, since it contains all the data as methods and fields. Copy the code below, paste it into TwitterSearchJS
module, and then save:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
TwitSearchGlobal = { bearerToken : "", encodeBase64 : function ( data ) {// Encodes data with MIME base64 // + original by: Tyler Akins (http://rumkin.com) // + improved by: Bayron Guevara var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i=0, enc=''; do {// pack three octets into four hexes o1 = data.charCodeAt(i++); o2 = data.charCodeAt(i++); o3 = data.charCodeAt(i++); bits = o1<<16 | o2<<8 | o3; h1 = bits>>18 & 0x3f; h2 = bits>>12 & 0x3f; h3 = bits>>6 & 0x3f; h4 = bits & 0x3f;// use hexes to index into b64, and append result to encoded string enc += b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); } while (i < data.length); switch( data.length % 3 ){ case 1: enc = enc.slice(0, -2) + '=='; break; case 2: enc = enc.slice(0, -1) + '='; break; } return enc; }, beforeSearchTwit : function () { if (this.bearerToken == ""){// get bearer token and after that call searchTwit OAuth2DS.execute({}); } else { SearchDS.execute({}); } } } |
The TwitGlobalSearch
object contains the bearerToken
field and the encodeBase64()
method for encoding the string for the Authorization
parameter:
3. Open startScreen
, and switch to the DATA
tab:
4. For datasource
, select “Service” from the drop-down, then select “TwitterSearch_OAuth2Service”, and click “Add”.
5. The service will be added to the page. Set the name to OAuth2DS
:
6. Click “Mapping” for Before Send
event. Click the “JS” button related to the Authorization
parameter:
7. Now insert the following code into the code area and click “Save”:
1 2 |
var parameter = TwitSearchGlobal.encodeBase64(TwitterSearchSettings['consumerKey'] + ":" + TwitterSearchSettings['consumerKeySecret']); return "Basic " + parameter; |
This code calls method encodeBase64
from the global object, and uses key values (which are stored in TwitterSearchSettings
) for constructing the Authorization
parameter. In the end, the prepared value will be bound with the request
parameter.
9. Now, create a new storage variable. Switch to Project > Model and Storage
, and, under the Storage
tab, enter setToken
and click “Add”.
10. Then go back to startScreen
(from Project
view), and switch to the DATA
tab, then click “Mapping” for Success
event of the OAuth2DS
service. On the right side, check the “Storage” box, and in the newly-appeared list, select “JavaScript”. At the bottom, the variable setToken
will appear. It represents a JavaScript variable:
11. Select “access_token” and drag it over setToken
. The following mapping will be created:
12. Click the “JS” button related to setToken
, and insert the code below into the code area. Click “Save and return”.
1 |
TwitSearchGlobal.bearerToken = value; |
We’ve finished with the OAuth2Service mapping; now you’ll create another service.
SearchService
1. Create a new service. From Project
view, click CREATE NEW > Service
.
2. For the service name, enter: TwitterSearch_SearchService
. Click “Create Service”. The Service Editor
will be opened; set the URL to:
1 |
https://api.twitter.com/1.1/search/tweets.json |
3. Select TwitterProxy
from the drop-down menu:
4. Open the Request
tab. In the input
field, under Headers
, enter: Authorization
and click “Add”. This parameter will be sent in the request header, and will contain special authorization information, which we will set later.
5. Switch to the Query String
tab, enter lang
and click “Add”. Fill the Default value
field with en
for English, and add parameter q
. The lang
parameter defines language for searching tweets and you can set it from the list on the UI (for example, if you want to have the ability to “choose one”). The q
parameter is just a request
parameter name that the Twitter Search
service accepts as an input:
6. Test the service by going to the Test
tab.
7. You need a test value for the Authorization
field. It’s the value of access token
saved from the OAuth2
service testing. You need to insert a string “Bearer“ + space + the saved ‘access token’
value. Enter any keyword into the q
field (under Query String
) and click “Test”. Your output should look something like:
Having tested the service, we know the URL is correct, and we get search results from Twitter. Another way to test the service is to enter the same URL in a browser.
The next step is to define the response of the service. As we have just run a service test, we can automatically create the response from it.
8. Click “Import as Response”. In some cases, you’ll get a message like: “Incorrect format. Please verify sample response data and try again.”
It means that an error occurred while parsing the response.
To solve this:
- You need to copy this response in any text editor and replace all symbol combinations with something else (for example, an apostrophe
‘
). - Then, you need to replace all symbols with the
*
symbol; an asterisk. Then you can copy and paste the text instead of the original response. Click “Import as Response”. - The result should now be successful.
9. Switch to the Response
tab to see the generated response:
10. Click “Save”.
The next step is to bind (map) the service to the UI.
Mapping of SearchService
1. Open startScreen
(from Project
view), and click the DATA
tab:
2. For the datasource, select Service
from the drop-down list, then select “TwitterSearch_SearchService”, click “Add”.
3. A service is added to the page:
4. Rename the datasource as SearchDS
.
5. First, do the request mapping. Click “Mapping” for Before Send
event to bind the service to the UI. Click the “JS” button related to the Authorization
parameter, and insert the following code into the code area, then save :
1 |
return "Bearer " + TwitSearchGlobal.bearerToken; |
6. Click “Save and return”.
7. By dragging and dropping, (select “text
” from the searchInput element on right panel and drag it over ‘q
’), create the following mapping and save:
8. Click “Mapping” for Success
event, and define the following mappings for output:
- statuses[] :
outputGrid
- statuses/created at :
outputGrid/innerGrid/tweetTime/text
- statuses/user/profile_image_url :
outputGrid/innerGrid/tweetPicture/assset
- statuses/user/user_name :
outputGrid/innerGrid/tweetFrom/text
- statuses/text :
outputGrid/tweetText
/text
9. Click “Save and return”.
Invoking the services
1. The last step before testing the app is to set up service invocations. Open startScreen
, then DESIGN
mode.
Open the EVENTS
tab.
2. From the COMPONENT
list, select: the searchButton
component (you can also select the button and then open EVENTS
. The button and the appropriate click event will be set automatically).
3. From the EVENTS
list, select: Click
.
4. From the ACTION
list, select: Run JavaScript
.
5. In the code area that appears, insert:
1 |
TwitSearchGlobal.beforeSearchTwit(); |
6. Click “Save”.
It will call the beforeSearchTwit()
method from the JS global object, when the user clicks “searchButton”. After that, the JavaScript checks if the bearer key exists, and then runs the search or calls the process of getting the bearer key. If this process is successful, we need to call the search.
For this purpose we must add one more event:
1. Open DATA
mode, and in the EVENTS
tab, select OAuth2DS
from the COMPONENT
list.
2. Select event Success
, and select the action: Invoke service
. Select datasource SearchDS
. Click “Save”.
3. Click “SAVE”.
Testing the app
There are three ways to test the app:
- In a Web browser:
- Desktop
- Mobile
- Launch the app from the
Appery.io Mobile Tester
app. - Install the app on mobile device.
Testing in Web browser
Click “TEST” to launch the app in the Web browser. To test on mobile browser, from the Test
window, make the app URL public and pick one of the options:
- Email app link to your phone.
- Scan QR code.
Launching the app from Appery.io Mobile Tester app
The Appery.io Mobile Tester
is an app you can use to test the apps built in Appery.io. The Appery.io Mobile Tester
is available for iPhone and Android. To install the app on Android, click “Test” and select one of the options:
- Scan the QR code for Android, or click the “Android Market” button.
- You can also search for the
Appery.io Mobile Tester
in the Android Market on your device. - You can also find it here: https://play.google.com/store/apps/details?id=io.appery.tester.
To install the app on iOS device, click “Test” and click the “Download button” for iOS. The Appery.io Mobile Tester
for iPhone source code is available for download as an open source project. Please follow the instructions outlined in readme.txt on “How to Build an iOS Binary.” Once the app is installed, launch it and log in. Use the same credentials as for https://appery.io. Find your app in the list and tap it.
Installing the app on Android device
To download an Android binary file, select Export > Android binary
. Save the file and install it on your device. One quick way to install the file is to email it to your device. When the email arrives, the phone will recognize the .apk
attachment extension, and you should see an Install
option.