Pages

Men

rh

10/28/2014

Add Mobile Services to an existing app

Add Mobile Services to an existing app

This topic shows you how to use a Azure Mobile Services to leverage data in an iOS app. In this tutorial, you will download an app that stores data in memory, create a new mobile service, integrate the mobile service with the app, and view the changes to data made when running the app.
The mobile service that you create in this tutorial supports the .NET runtime in the Mobile Service. This allows you to use .NET languages and Visual Studio for server-side business logic in the mobile service. To create a mobile service that lets you write your server-side business logic in JavaScript, see the JavaScript backend version of this topic.
This tutorial walks you through these basic steps:
  1. Download the iOS app project
  2. Create the mobile service
  3. Download the service locally
  4. Test the mobile service
  5. Publish the mobile service to Azure
  6. Update the app to use Mobile Services
  7. Test the app against Mobile Services
This tutorial requires the following:

Download the GetStartedWithData project

This tutorial is built on the GetStartedWithData app, which is an iOS app. The UI for this app is identical to the app generated by the Mobile Services iOS quickstart, except that added items are stored locally in memory.
  1. Download the GetStartedWithData sample app.
  2. In Xcode, open the downloaded project and examine the TodoService.m file.
    Notice that there are eight // TODO comments that specify the steps you must take to make this app work with your mobile service.
  3. Press the Run button (or the Command+R key) to rebuild the project and start the app.
  4. In the app, type some text in the text box, then click the + button.
    Notice that the saved text is displayed in the list below.

Create a new mobile service in the Management Portal

Follow these steps to create a new mobile service.
  1. Log into the Management Portal.
  2. At the bottom of the navigation pane, click +NEW.
  3. Expand Compute and Mobile Service, then click Create.
    This displays the New Mobile Service dialog.
  4. In the Create a mobile service page, select Create a free 20 MB SQL Database, select .NET runtime, then type a subdomain name for the new mobile service in the URL textbox and wait for name verification. Once name verification completes, click the right arrow button to go to the next page.
    This displays the Specify database settings page.
    NOTE
    As part of this tutorial, you create a new SQL Database instance and server. You can reuse this new database and administer it as you would any other SQL Database instance. If you already have a database in the same region as the new mobile service, you can instead choose Use existing Database and then select that database. The use of a database in a different region is not recommended because of additional bandwidth costs and higher latencies.
  5. In Name, type the name of the new database, then type Login name, which is the administrator login name for the new SQL Database server, type and confirm the password, and click the check button to complete the process.
    NOTE
    When the password that you supply does not meet the minimum requirements or when there is a mismatch, a warning is displayed. 
    We recommend that you make a note of the administrator login name and password that you specify; you will need this information to reuse the SQL Database instance or the server in the future.
You have now created a new mobile service that can be used by your mobile apps.

Download the service to your local computer

  1. In the Azure Management Portal, click your new Mobile Service or its cloud icon tab to go to the overview page.
  2. Click the iOS platform. Under the Get Started section, and expand Create a new iOS app.
  3. If you haven't already done so, download and install Visual Studio Professional 2013, or a later version.
  4. Click Download under Download and publish your service to the cloud.
    This downloads the Visual Studio project that implements your mobile service. Save the compressed project file to your local computer, and make a note of where you saved it.
  5. Scroll down to the bottom of that Get Started section to the step titled Download and publish your service to the cloud. Click the link shown in the screenshot below to download a publish profile file for the mobile service you just downloaded.

Test the mobile service

The mobile service project that you download lets you to run your new mobile service right on your local computer or virtual machine. This makes it easy to debug your service code before you even publish it to Azure.
  1. Browse to the location where you saved the compressed project files, expand the files on your computer, and open the solution file in Visual Studio.
  2. Press the F5 key to rebuild the project and start the mobile service locally.
    A web page is displayed after the mobile service starts successfully.

Publish the mobile service to Azure

After testing the client app against the local mobile service, the final stage of this tutorial is to publish the mobile service to Azure and run the app against the live service.
  1. In Solution Explorer, right-click the mobile service project, click Publish, then in the Publish Web dialog box click Azure Mobile Services.
  2. Sign in with your Azure account credentials, select your service from Existing Mobile Services, and click OK.
    Visual Studio downloads your publish settings directly from Azure.
  3. Click Validate connection to verify that publishing is correctly configured, then click Publish.
    After publishing succeeds, you will again see the confirmation page that the mobile service is up and running, this time in Azure.

Update the app to use the mobile service for data access

Now that your mobile service is ready, you can update the app to store items in Mobile Services instead of the local collection.
  1. If you haven't already installed the Mobile Services iOS SDK, install it now. Once installed, copy the WindowsAzureMobileServices.framework directory and over-write the WindowsAzureMobileServices.framework directory included in the downloaded project. This way, you are using the very latest Azure Mobile Services SDK.
  2. In the TodoService.h file, locate the following commented line of code:
    // TODO - create an MSClient proeprty
    After this comment, add the following line of code:
    @property (nonatomic, strong)   MSClient *client;
    This creates a property that represents the MSClient that connects to the service
  3. In the file TodoService.m, locate the following commented line of code:
    // TODO - create an MSTable property for your items
    After this comment, add the following line of code inside the @interface declaration:
    @property (nonatomic, strong)   MSTable *table;
    This creates a property representation for your mobile services table.
  4. In the Management Portal, click Mobile Services, and then click the mobile service you just created.
  5. Click the Dashboard tab and make a note of the Site URL, then click Manage keys and make a note of the Application key.
    You will need these values when accessing the mobile service from your app code.
  6. Back in Xcode, open TodoService.m and locate the following commented line of code:
    // Initialize the Mobile Service client with your URL and key.
    After this comment, add the following line of code:
    self.client = [MSClient clientWithApplicationURLString:@"APPURL" applicationKey:@"APPKEY"];
    This creates an instance of the Mobile Services client.
  7. Replace the values of APPURL and APPKEY in this code with the URL and application key from the mobile service that you acquired in step 6.
  8. Locate the following commented line of code:
    // Create an MSTable instance to allow us to work with the TodoItem table.
    After this comment, add the following line of code:
    self.table = [self.client tableWithName:@"TodoItem"];
    This creates the TodoItem table instance.
  9. Locate the following commented line of code:
    // Create a predicate that finds items where complete is false
    After this comment, add the following line of code:
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"complete == NO"];
    This creates a query to return all tasks that have not yet been completed.
  10. Locate the following commented line of code:
    // Query the TodoItem table and update the items property with the results from the service
    Replace that comment and the subsequent completion block invocation with the following code:
    [self.table readWhere:predicate completion:^(NSArray *results, NSInteger totalCount, NSError *error)
    {
       self.items = [results mutableCopy];
       completion();
    }];
  11. Locate the addItem method, and replace the body of the method with the following code:
    // Insert the item into the TodoItem table and add to the items array on completion
    [self.table insert:item completion:^(NSDictionary *result, NSError *error) {
        NSUInteger index = [items count];
        [(NSMutableArray *)items insertObject:item atIndex:index];
    
        // Let the caller know that we finished
        completion(index);
    }];
    This code sends an insert request to the mobile service.
  12. Locate the completeItem method, and locate the following commented line of code:
    // Update the item in the TodoItem table and remove from the items array on completion
    Replace the body of the method, from that point to the end of the method, with the following code:
    // Update the item in the TodoItem table and remove from the items array on completion
    [self.table update:mutable completion:^(NSDictionary *item, NSError *error) {
    
        // Get a fresh index in case the list has changed
        NSUInteger index = [items indexOfObjectIdenticalTo:mutable];
    
        [mutableItems removeObjectAtIndex:index];
    
        // Let the caller know that we have finished
        completion(index);
    }];
    This code removes TodoItems after they are marked as completed.
  13. In TodoListController.m, locate the onAdd method and overwrite it with the following code:
    • (IBAction)onAdd:(id)sender { if (itemText.text.length == 0) { return; }
      NSDictionary *item = @{ @"text" : itemText.text, @"complete" : @NO }; UITableView *view = self.tableView; [self.todoService addItem:item completion:^(NSUInteger index) { NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0]; [view insertRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationTop]; }];
      itemText.text = @""; }
Now that the app has been updated to use Mobile Services for backend storage, it's time to test the app against Mobile Services.

Test the app against your new mobile service

  1. In Xcode, select an emulator to deploy to (either iPhone or iPad), press the Run button (or the Command+R key) to rebuild the project and start the app.
    This executes your Azure Mobile Services client, built with the iOS SDK, that queries items from your mobile service.
  2. As before, type text in the textbox, and then click the + button..
    This sends a new item as an insert to the mobile service. Each new todoItem is stored and updated in the SQL database you previously configured for your mobile service in the Azure Management Portal.
  3. Stop and restart the app to see that the changes were persisted to the database in Azure.
    You can also examine the database using the Azure Management portal or Visual Studio's SQL Server Object Explorer. The next two steps use the Azure Management portal to view the changes in your database.
  4. In the Azure Management Portal, click manage for the database associated with your mobile service.
  5. In the Management portal execute a query to view the changes made by the app. Your query will be similar to the following query but use your database name instead of todolist.
    SELECT * FROM [todolist].[todoitems]
This concludes the Get started with data tutorial.
Source from :http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-ios-get-started-data/

No comments :

Post a Comment