Use the Twilio cloud service to add text messaging to Android and iOS apps

21 August 2014
PDF (789 KB)
Share:
Susan Rizzo

Susan Rizzo

Software Engineer, IBM Mobile Cloud Services

Google+

author photo - belinda johnson

Belinda Johnson

Software Engineer, IBM Mobile Cloud Services

@BeeMarieJohnson

Sign up for IBM Bluemix
This cloud platform is stocked with free services, runtimes, and infrastructure to help you quickly build and deploy your next mobile or web application.

You may already know about some of the benefits of Bluemix, IBM's open platform for developing and deploying mobile and web applications. The many pre-built services in Bluemix make it easy to build and enhance applications.

In this tutorial, we'll use Bluemix services to extend an Android or iOS application called BlueList using the Twilio service. Other tutorials in this series show you how to add more cloud-based services to your apps. The BlueList application is a simple mobile app that uses Bluemix services. With the free services on Bluemix, you can get started writing and extending your own applications in no time.

In the previous tutorials, "Build an Android app using the IBM Mobile Data for Bluemix service" and "Build an iOS app using the IBM Mobile Data for Bluemix service," we added the IBM Mobile Data for Bluemix service where items in a list persist. In this tutorial, we'll add the Twilio service to the BlueList app so text notifications are sent when one of the devices updates the list in some way, and the list is then updated on all devices.

With the free services on Bluemix, you can get started writing and extending your own applications in no time.

Get the code

 

If you skipped the previous tutorial in this series, you can start with the bluelist-mobiledata code but will need to perform the catch-up tasks below before adding the Twilio service. If you worked through the previous tutorial, you can start with your existing code and follow the steps below to add the Twilio service.

To jump ahead by downloading the bluelist-twilio (TW) code, you'll need to perform a few steps to get the BlueList app with the IBM Mobile Data for Bluemix and Twilio service working. The bluelist-twilio (TW) code includes the changes made to the bluelist-mobiledata code in this tutorial.

What you need for your application

 
  • Familiarity with the previous tutorials in this series, mentioned above, where we added the IBM Mobile Data for Bluemix service to a mobile app. That app is the starting point for this tutorial.
  • For Android: Familiarity with Android development and an Android development environment. We used Eclipse with ADT, but feel free to use your preferred environment.

    NOTE: If you decide to use Android Studio, you can skip step 3.2 (the second step under Make client-side code changes) since the gradle.build file provided in the Android root directory will pull in the required dependencies. Please check it out, familiarize yourself with the Gradle build code, and uncomment the required dependencies.

  • For iOS: Familiarity with iOS development and an iOS development environment.
  • Familiarity with git to download the bluelist-mobiledata and bluelist-twilio IBM Bluemix Mobile Cloud Samples.
  • The bluelist-mobiledata code (above) or your existing code from the previous tutorial in the series.
  • The bluelist-twilio code (above) for the Twilio Node.js application server-side code required to interface with the Twilio service.
  • A Twilio account with its associated Account SID, Auth token, Twilio phone number, and a voice/text verified phone number. Read how to get this at Twilio.com or follow our instructions.
  • Familiarity with the cf command-line tool to push the Twilio Node.js server-side code for your Bluemix application.

Limitations

This tutorial is based on using Twilio's Free Trial setup and REST API. With the trial, there are a few restrictions:

  • SMS messages will be prefixed with the string "Sent from a Twilio trial account."
  • SMS messages must be sent to a verified phone number, as shown in this message: Image shows that SMS messages must be sent to a verified phone number

Catch-up tasks (Android)

 

If you skipped the previous tutorial in this series, get caught up:

  1. If you haven't already done so, download the bluelist-mobiledata code and import project bluelist-mobiledata-android into your Android development environment. Any compile errors seen after the project import will be corrected once you complete the remaining catch-up steps.
  2. Go to Step 1. Create a Mobile Cloud application on Bluemix in the previous tutorial in this series and perform steps 1.1–1.10. These steps will walk you through:
    • Login and creation of an application named BlueList on Bluemix
    • Downloading the Android SDK
    • Updating the bluelist.properties file with your BlueList app values
    • The addition of JAR files to your libs directory
  3. Save your Bluemix application name. You'll need the application name later.
  4. Once you complete these steps, run this code in your emulator or device to verify your Android development environment is set up correctly before you add the Twilio service. You should now be able to perform Steps 7 and 8 in the previous tutorial.

If the application runs successfully, you are all caught up and ready to add Twilio and server-side cloud services.

Catch-up tasks (iOS)

 

If you skipped the previous tutorial in this series, get caught up:

  1. If you haven't already done so, download the bluelist-mobiledata code and import the bluelist-mobiledata-iOS code into your iOS development environment.
  2. Go to Step 1. Create a Mobile Cloud application on Bluemix in the previous tutorial in this series and perform steps 1.1–1.6 and steps 2.1-2.7. These steps will walk you through:
    • Login and creation of an application named BlueList on Bluemix
    • Downloading the iOS SDK
    • Updating the bluelist.plist file with your BlueList app values
    • The addition of JAR files to your libs directory
  3. Save your Bluemix application name. You'll need the application name later.
  4. Once you complete these steps, run this code in your emulator or device to verify that your Android development environment is set up correctly before you add the Twilio service. You should now be able to perform steps 6 and 7 in the previous tutorial.

If the application runs successfully, you are all caught up and ready to add Twilio and server-side cloud services.

Set up your Twilio account

 

Before you start, set up your Twilio account:

  1. Go to Twilio and sign up for a free trial account.
  2. Enter the required information (name, email, password) and click Get Started.
  3. Enter a valid (real) phone number so Twilio can verify that you're a human and complete the verification.

    Note: This number will also be the number your BlueList grocery list application will text.

  4. Once the verification completes, you will be assigned a Twilio phone number. You have the option of accepting the assigned phone number or choosing your own. Save your Twilio phone number because you will need it again shortly.
  5. Complete the setup of your account. Click on the DASHBOARD page and you'll see your ACCOUNT SID and AUTH TOKEN. Save these values; you will need them later. To copy/paste the TOKEN, click on the lock icon, as pictured below.
Image shows lock icon

Extend your BlueList app with Twilio

 

Step 1. Add Twilio service to your application in Bluemix

 
  1. Log in to Bluemix.
  2. Assuming you've completed the steps in the previous tutorial or the catch-up steps above, click on your application in the DASHBOARD view.
  3. Click on ADD A SERVICE and add the Twilio service to your application. Image shows adding Twilio service
  4. You will be prompted for the Account SID and Auth Token for your Twilio account. Select your app from the Select an application drop-down, then (copy/paste) the Twilio values you saved earlier and click CREATE. Image shows completing the addition of TwilioNote: Your new Twilio service will be assigned a name (i.e., Twilio-xx), but you can change it to whatever you'd like. In this example, the Twilio service name is "Twilio."
  5. Save your Twilio service name; you will need it when you edit the Node.js application code.
  6. Your application will need to be restarted. Click OK to restart your BlueList application.
  7. Now when you look at your Bluemix dashboard, you should see the new Twilio service added to your BlueList application. Image shows Twilio in BlueList
  8. Click on your BlueList application to go to the overview page.
  9. Click on the Runtime link to view the details of your BlueList Node.js runtime. Image shows BlueList Node.js runtime
  10. Scroll to the Environment Variables section and the VCAP_SERVICES tab. Image shows VCAP_SERVICES

    Click to see larger image

  11. Review the "user-provided" section of the JSON code. This section was created when you added the Twilio service to your application. We will be able to use the VCAP_SERVICES variables to dynamically retrieve the Twilio accountSID and authToken values within our Node.js runtime code. Using the ibmconfig module within our server-side code allows us to access these Bluemix application environment variables. Image shows JSON code

Step 2. Familiarize yourself with the server-side Node.js Twilio code

 
  1. If you haven't already done so, use git to download the Twilio Node.js application code from IBM DevOps Services. The Node.js code is in the bluelist-twilio-node subfolder.
  2. Look through the code in the <gitRepository>/bluelist-twilio/bluelist-twilio-node directory — specifically, the app.js file — and familiarize yourself with the code.
  3. The app.js file will require a few updates, which we'll walk through now. Open app.js in an editor and make the following updates:
    • Replace the applicationId and applicationRoute value placeholders with your application values. These values can be found on your application's Bluemix overview page.
    • Update the toPhone and fromPhone value placeholders. Replace the toPhone number with the phone number to be sent the text message and the fromPhone phone number with your assigned Twilio phone number.
      //change these to your Bluemix application values
      var appConfig = {
          applicationId: "<INSERT_APPLICATION_ID_HERE>",
          applicationRoute: "<INSERT_APPLICATION_ROUTE_HERE>"
      };
      //change these to your Twilio values
      var twilioConfig = {
          twilioServiceName: "<INSERT_TWILIO_SERVICE_NAME>",
          toPhone: "+15551234567",
          fromPhone: "+15557654321"
      };
  4. Edit the manifest.yml file. Update the host: and name: values to match the name of your Bluemix application.
    host: my_bluemix_app_name
    disk: 1024M
    name: my_bluemix_app_name
    command: node app.js
    path: .
    domain: mybluemix.net
    mem: 128M
    instances: 1
  5. Save your changes and prepare to use the Cloud Foundry command-line interface (cf) to push your code up to Bluemix.
  6. Open a command prompt and navigate to the location of your Twilio Node.js application. For example: cd <gitRepository>/bluelist-twilio-node/bluelist_twilio. List the directory contents to make sure you see your app.js, manifest.yml, and package.json files (among others).
  7. Verify that cf is installed correctly by issuing the following command:
    cf –version
  8. The command results should display the version of cf installed on your machine. For example:
    cf version 6.0.1-9df4861
  9. Log in to Bluemix using the following command:
    cf login -a https://api.ng.bluemix.net
  10. Push (upload) your new application code up to the Bluemix Node.js runtime by running the following command, replacing ${yourBlueList} with your application name:
    cf push ${yourBlueList} -p . -m 512M
  11. Confirm that the push command was successful and your new Twilio Node.js application is running on Bluemix.

    Click to see code listing

    		1 of 1 instances running
    		
    		App started
    		
    		Showing health and status for app ${yourBlueList} in org ${yourOrg} / space ${yourSpace} as ${yourBlueMixId}...
    		OK
    		
    		requested state: started
    		instances: 1/1
    		usage: 512M x 1 instances
    		urls: ${yourBlueList}.mybluemix.net
    		
    		     state     since                    cpu    memory          disk
    		#0   running   2014-05-01 05:42:56 PM   0.0%   54.6M of 512M   34.7M of 1G

Step 3 (Android). Make client-side code changes

 

Assuming you've completed the steps in the previous tutorial or the catch-up steps above, we're going to start making changes to the client-side Android project code to bring it up to the TW level and interact with the Twilio Node.js runtime you just set up.

  1. Open your Android development environment so you can make the necessary code changes.
  2. (Skip this step if you're using Android Studio.) To use the server-side cloud code, we need an additional Android SDK JAR file. Navigate to the Android SDK, unzipped during the previous tutorial or catch-up steps, and copy ibmcloudcode.jar to your libs folder. Your libs directory should now look like the following figure. Image shows libs directory
  3. Edit the bluelist.properties file in your assets folder. If not already done, update the applicationID value with your Bluemix application ID. Add two new property values to the file: applicationNAME and twilioTextMessage. The applicationNAME should match your Bluemix application name; the twilioTextMessage is the message text Twilio will send to your phone.
    applicationID=<INSERT_APPLICATION_ID_HERE>
    applicationSecret=<INSERT_APPLICATION_SECRET_HERE>
    applicationRoute=<INSERT_APPLICATION_ROUTE_HERE>
    # Text preceding grocery list (keep < 30 chars to allow room for list items) 
    twilioTextMessage=Pick up groceries:
  4. Edit the BlueListApplication.java file and get ready to make some changes.
  5. Create a new Activity variable to track the grocery list activity status.
    publicfinalclass BlueListApplication extends Application {
    	private Activity mActivity;
    	publicstaticfinalintEDIT_ACTIVITY_RC = 1;
    	privatestaticfinal String
    		CLASS_NAME = BlueListApplication.class.getSimpleName();
    	privatestaticfinal String APP_ID = "applicationID";
    	privatestaticfinal String PROPS_FILE = "bluelist.properties";
    	List<Item> itemList;
  6. Track the activity status within four of the ActivityLifecycleCallbacks (create, started, resumed, and paused).

    Click to see code listing

    public BlueListApplication() {
    		registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
    			@Override
    			publicvoid onActivityCreated(Activity activity,Bundle savedInstanceState) {
    				Log.d(CLASS_NAME, "Activity created: " + activity.getLocalClassName());
    				// Track activity
    				mActivity = activity;
    			}
    			@Override
    			publicvoid onActivityStarted(Activity activity) {
    				Log.d(CLASS_NAME, "Activity started: " + activity.getLocalClassName());
    				// Track activity
    				mActivity = activity;
    			}
    			@Override
    			publicvoid onActivityResumed(Activity activity) {
    				Log.d(CLASS_NAME, "Activity resumed: " + activity.getLocalClassName());
    				// Track activity
    				mActivity = activity;
    			}
    			@Override
    			publicvoid onActivitySaveInstanceState(Activity activity,Bundle outState) {
    				Log.d(CLASS_NAME, "Activity saved instance state: " + 							activity.getLocalClassName());
    			}
    			@Override
    			publicvoid onActivityPaused(Activity activity) {
    				Log.d(CLASS_NAME, "Activity paused: " + activity.getLocalClassName());
    				// Track activity
    				if (activity != null && activity.equals(mActivity))
    		    		mActivity = null;
    			}
    			@Override
    			publicvoid onActivityStopped(Activity activity) {
    				Log.d(CLASS_NAME, "Activity stopped: " + activity.getLocalClassName());
    			}
    			@Override
    			publicvoid onActivityDestroyed(Activity activity) {
    				Log.d(CLASS_NAME, "Activity destroyed: " + activity.getLocalClassName());
    			}
    		});
  7. Modify the Bluemix initialization call.
    // initialize the IBM core backend-as-a-service
    IBMBluemix.initialize(this, props.getProperty(APP_ID), 
    				props.getProperty(APP_SECRET), props.getProperty(APP_ROUTE));
  8. Save your changes to BlueListApplication.java. You may see some warnings at this point, but they should be resolved as you continue making code updates.
  9. Edit the MainActivity.java file and get ready to make some changes.
  10. Define some new variables to retrieve information from the bluelist.properties file.
    	/* Define values found in properties file */
    	private static final String TWILIO_TEXT_MSG = "twilioTextMessage";
    	private static final String PROPS_FILE = "bluelist.properties";
    	private static String twilioTextMessage;
  11. After /* refresh the list */ (in onCreate), add code to read the bluelist.properties file.
    	/* refresh the list */
    	listItems();
    		
    	/* get text message from properties file */
    	Properties props = new java.util.Properties();
    	Context context = getApplicationContext();
    	try {
    		AssetManager assetManager = context.getAssets();					
    		props.load(assetManager.open(PROPS_FILE));
    		Log.i(CLASS_NAME, "Found configuration file: " + PROPS_FILE);
    	} catch (FileNotFoundException e) {
    		Log.e(CLASS_NAME, "The bluelist.properties file was not found.", e);
    	} catch (IOException e) {
    		Log.e(CLASS_NAME, "The bluelist.properties file could not be read properly.", e);
    	}
    	Log.i(CLASS_NAME, "Twilio Text Message to send is: " + props.getProperty(TWILIO_TEXT_MSG));
    	twilioTextMessage =  props.getProperty(TWILIO_TEXT_MSG);
  12. Add a new method, updateOtherDevices(), to make the call to our server-side cloud module. Note the twilioTextMessage defined in the bluelist.properties file is passed via a JSONObject on the POST request.
    	private void updateOtherDevices() {
    		// initialize and retrieve an instance of the IBM CloudCode service
    		IBMCloudCode.initializeService();
    		IBMCloudCode myCloudCodeService = IBMCloudCode.getService();
    		JSONObject jsonObj = new JSONObject();
    		try {
    			jsonObj.put("text", twilioTextMessage);
    		} catch (JSONException e) {
    			e.printStackTrace();
    		}
    		// Call the node.js application hosted in the IBM Cloud Code service
    		// with a POST call, passing in a non-essential JSONObject
    		// The URI is relative to, appended to, the Bluemix context root
    		myCloudCodeService.post("notifyOtherDevices", jsonObj);
    	}
  13. Now we just need to add the calls to updateOtherDevices. Add a call when an edit is made, a new item is created, or an existing item is deleted.
    • Edit code
          public void onActivityResult(int requestCode, int resultCode, Intent data) {
      		switch (resultCode)
      		{
      		/* if an edit has been made, notify that the data set has changed. */
      		case BlueListApplication.EDIT_ACTIVITY_RC:
      			updateOtherDevices();
      			sortItems(itemList);
      			lvArrayAdapter.notifyDataSetChanged();
      			break;
      		}
      	}
    • Create code

      Click to see code listing

      	public void createItem(View v) {
      		EditText itemToAdd = (EditText) findViewById(R.id.itemToAdd);
      		String toAdd = itemToAdd.getText().toString();
      		Item item = new Item();
      		if (!toAdd.equals("")) {
      			item.setName(toAdd);
      			// Save the item list using the IBMDataObject
      			item.save().continueWith(new Continuation<IBMDataObject, Void>() {
      			
      				@Override
      				public Void then(Task<IBMDataObject> task) throws Exception {
      
      					 // Log error message, if the save task fail.
      					if (task.isFaulted()) {
      						Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
      						return null;
      					}
      
      					 // If the result succeeds, load the list
      					if (!isFinishing()) {
      						listItems();
      						updateOtherDevices();
      					}
      					return null;
      				}
      
      			});
      
      			// set text field back to empty after item added
      			itemToAdd.setText("");
      		}
      	}
    • Delete code

      Click to see code listing

      	public void deleteItem(Item item) {
      		itemList.remove(listItemPosition);
      		// This will attempt to delete the item on the server
      		item.delete().continueWith(new Continuation<IBMDataObject, Void>() {
      
      			@Override
      			public Void then(Task<IBMDataObject> task) throws Exception {
      
      				 // Log error message, if the delete task fail.
      				if (task.isFaulted()) {
      					Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
      					return null;
      				}
      
      				 // If the result succeeds, reload the list
      				if (!isFinishing()) {
      					runOnUiThread(new Runnable() {
      						public void run() {
      							updateOtherDevices();
      							lvArrayAdapter.notifyDataSetChanged();
      						}
      					});
      				}
      				return null;
      			}
      		});
      		lvArrayAdapter.notifyDataSetChanged();
      	}
  14. Save your changes to MainActivity.
  15. All the code changes should now be complete. Don't forget to use Eclipse to organize imports (Ctrl+Shift+O). This will automatically import any required elements from the SDK JARs you copied into the project earlier. If you still have compile errors due to missing import statements, ensure that the following imports have been added to MainActivity.java.
    	import java.util.Properties;
    	import org.json.JSONException;
    	import org.json.JSONObject;
    	
    	import bolts.Continuation;
    	import bolts.Task;
    	
    	import com.ibm.mobile.services.cloudcode.IBMCloudCode;
    	import com.ibm.mobile.services.data.IBMDataException;
    	import com.ibm.mobile.services.data.IBMDataObject;
    	import com.ibm.mobile.services.data.IBMQuery;

Step 3 (iOS). Make client-side code changes

 

Assuming you've completed the steps in the previous tutorial or the catch-up steps above, we're going to start making changes to the client-side Android project code to bring it up to the TW level and interact with the Twilio Node.js runtime you just set up.

  1. Open your iOS development environment so you can make the necessary code changes.
  2. To use the server-side cloud code, we need an additional iOS SDK JAR file. In Finder, locate the iOS SDK, unzipped during the previous tutorial or catch-up steps, and drag the IBMCloudCode framework into the BlueList Xcode project under the Frameworks folder. Image shows libs directory

    Click to see larger image

  3. Edit the bluelist.plist file in your Supporting Files folder. If not already done, update the applicationId, applicationSecret, and applicationRoute values with your Bluemix app values. Add one new property value to the file: twilioTextMessage. The twilioTextMessage is the message text Twilio will send to your phone. Image shows updating the applicationId

    Click to see larger image

  4. Open IBM_AppDelegate.m and add support for the use of server-side cloud code. Add a new #import statement, IBM_AppDelegate() interface, and initialize the IBMCloudCode service. Add the IBMCloudCode initialization immediately after the existing IBMData initialization.
    #import "IBM_AppDelegate.h"
    #import <IBMBluemix/IBMBluemix.h>
    #import <IBMData/IBMData.h>
    #import <IBMCloudCode/IBMCloudCode.h>
                                    
    @interface IBM_AppDelegate ()
    @end
                                    
    @implementation IBM_AppDelegate
                                    
    . . .
                                    
    if(hasValidConfiguration){
        // Initialize the SDK and BlueMix services
        [IBMBluemix initializeWithApplicationId:applicationId
            andApplicationSecret:applicationSecret
                andApplicationRoute:applicationRoute];
        [IBMData initializeService];
        [IBMCloudCode initializeService];
    }else{
        [NSException raise:@"InvalidApplicationConfiguration" format: @"%@", errorMessage]
    }
  5. Save your changes to IBM_AppDelegate.m.
  6. Open IBM_ListViewController.m to make multiple code changes. Add a new #import statement for the IBMCloudCode and add some new properties to reference the IBMCloudCode service and Twilio text message.
    #import "IBM_ListViewController.h"
    #import "IBM_CreateEditItemViewController.h"
    #import "IBM_Item.h"
    #import <IBMCloudCode/IBMCloudCode.h>
    
    . . .
    
    // If edit was triggered, the cell being edited.
    @property UITableViewCell *editedCell;
    
    @property IBMCloudCode *cloudCodeService;
    @property NSDictionary *jsonDict;
    @property NSString *twilioText;
    
    @property NSData *jsonData;
  7. Add code to initialize the IBMCloudCode service and read the Twilio text message from the bluelist.plist file.

    Click to see code listing

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.itemList = [[NSMutableArray alloc]init];
    
    	// Initialize cloud code service
    	self.cloudCodeService = [IBMCloudCode service];
    
        // Setting up the refresh control
    	self.refreshControl = [[UIRefreshControl alloc]init];
    	self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"Loading Items"];
    	[self.refreshControl addTarget:self  action:@selector(handleRefreshAction)                                        
                                                            forControlEvents:UIControlEventValueChanged];
    
    	// Load initial set of items
    	[self.refreshControl beginRefreshing];
    	[self listItems:^{
            [self.refreshControl endRefreshing];
    	}];
    
    	//read the twilio text message from the .plist file
    	NSString *configurationPath = [[NSBundle mainBundle] pathForResource:@"configuration" ofType:@"plist"];
    	if(configurationPath){
            NSDictionary *configuration = [[NSDictionary alloc] initWithContentsOfFile:configurationPath];
            self.twilioText = [configuration objectForKey:@"twilioTextMessage"];
            if (!self.twilioText) {
                self.twilioText = @"Pick up groceries:";
            }
    	}
    	//set NSDictionary to text preface from .plist file.
    	self.jsonDict = [NSDictionary dictionaryWithObjectsAndKeys: self.twilioText, @"text", nil];
    }
  8. Update the createItemupdateItem, and deleteItem methods to make the call to our server-side cloud module. Note the twilioTextMessage defined in the bluelist.plist file is passed via a JSON object on the POST requests. Also note that we are utilizing Bolts chaining for the call to cloud code.
    - (void) createItem: (IBM_Item*) item
    {
        [self.itemList addObject: item];
        [self reloadLocalTableData];
        //save the new item and then notify other devices via cloud code for twilio notifications
        [[[item save] continueWithSuccessBlock:^id(BFTask *task) {
            return [self.cloudCodeService post:@"notifyOtherDevices" withJsonPayload: self.jsonDict];
        }] continueWithBlock:^id(BFTask *task) {
            if(task.error) {
                NSLog(@"createItem failed with error: %@", task.error);
            }
            return nil;
        }];
        
    }
    - (void) updateItem: (IBM_Item*) item
    {
        self.editedCell.textLabel.text = item.name;
        //save the updated item and then notify other devices via cloud code for twilio notifications
        [[[item save] continueWithSuccessBlock:^id(BFTask *task) {
            NSLog(@"in continueWithSuccessBlock");
            return [self.cloudCodeService post:@"notifyOtherDevices" withJsonPayload: self.jsonDict];
        }] continueWithBlock:^id(BFTask *task) {
            NSLog(@"in continueWithBlock");
            if(task.error) {
                NSLog(@"updateItem failed with error: %@", task.error);
            }
            return nil;
        }];
        
    }
    
    -(void) deleteItem: (IBM_Item*) item
    {
        [self.itemList removeObject: item];
        [self reloadLocalTableData];
        //delete the item and then notify other devices via cloud code for twilio notifications
        [[[item delete] continueWithSuccessBlock:^id(BFTask *task) {
            return [self.cloudCodeService post:@"notifyOtherDevices" withJsonPayload: self.jsonDict];
        }] continueWithBlock:^id(BFTask *task) {
            if(task.error) {
                NSLog(@"deleteItem failed with error: %@", task.error);
            }
            return nil;
        }];
        
        // Exit edit mode to avoid need to click Done button
        [self.tableView setEditing:NO animated:YES];
    }
  9. Save your changes to IBM_ListViewController.m.
  10. All the code changes should now be complete.

Step 4. Run the app

 

Now that you've made the code changes, your code should be equivalent to the bluelist-twilio version. To verify that all is well:

  1. Run the updated code in your emulator.
  2. Add some grocery list items.
  3. Check your phone (the one entered as the toPhone: number in your app.js code) for Twilio text messages as you update your grocery list. Image shows BlueList updates on your phone

Conclusion

 

So there you have it. Extending this mobile application using the Twilio service available in Bluemix should give you a sense of how easy it is to consume and integrate mobile data capabilities using mobile cloud services.

Add a comment

Note: HTML elements are not supported within comments.


1000 characters left

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Mobile development, Cloud computing
ArticleID=975485
ArticleTitle=Use the Twilio cloud service to add text messaging to Android and iOS apps
publish-date=08212014