Creating a mobile store

Dylan Mckee profile picture Written by: Dylan Mckee - Published on: 04 Nov 2015
In this tutorial, we’ll be taking you through the process of creating your first iOS mobile store app with Moltin in Objective-C.

The Moltin iOS SDK offers the perfect solution for mobile developers looking to incorporate eCommerce into their iOS app quickly and easily, all through native Objective-C or Swift code - and entirely without the pain of having to write, deploy and host a backend. The backend is entirely managed by Moltin, meaning you can work on creating great mobile store experiences for your iOS users without any fuss, developing high-quality native eCommerce apps rapidly with the Moltin iOS SDK.

Requirements

Getting set up

Firstly, create your Xcode project using the Master-Detail Application template. In this template, the master UITableView will display the store’s products, and the ‘detail’ view will contain product information.

Then, open a new Terminal window in the directory of your project and run `pod init` - this will get your project ready for CocoaPods. Open up the Podfile in your project directory using your favorite text editor, and add the line pod ‘Moltin’, this will add the Moltin SDK to your project. Then, run the pod install command in Terminal, open up the created .xcworkspace in Xcode, and you’ve successfully installed the Moltin iOS SDK.

Now, find your store’s Client ID from your Moltin account - you’ll need to include this in the app in the next step of this tutorial. Also, ensure that you create some mock products in your store so that you can see them in your iOS app. You can do this via the API or from the backend dashboard.

Setting up the SDK

Head to the MasterDetailView.m file in your Xcode project and import the Moltin SDK by adding the line #import <Moltin/Moltin.h> at the top of the file (underneath the other #import statements). Then, in the viewDidLoad method in that file, add [[Moltin sharedInstance] setPublicId:@"YOUR_STORE_ID"]; (obviously replacing YOUR_STORE_ID with the client ID of your store from the Moltin dashboard). This initializes the SDK for use with your Moltin store.

Listing Products

Now, in your MasterDetailView.m file, let’s get the products from the Moltin
API by adding the following code to your viewDidLoad method:

  [[[Moltin sharedInstance] product] listingWithParameters:nil success:^(NSDictionary *response) {
  // The array of products is at the "result" key
  self.objects = [response objectForKey:@"result"];
  
  // Reload the table view that'll be used to display the products...
  [self.tableView reloadData];
  
} failure:^(NSDictionary *response, NSError *error) {
  // Something went wrong!
   NSLog(@"error = %@", error);
}];

This code uses the SDK's listing WithParameters method, with empty parameters, to return every product in your store from the Moltin API, then populates the objects array with the returned products, and refreshes the table view that we’ll be displaying your products in.

Now to get the products displaying. To do this, replace the code in the cellForRowAtIndexPath method with:

  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

  NSDate *object = self.objects[indexPath.row];
  cell.textLabel.text = [object valueForKey:@"title"];

  return cell;

This creates a table view cell with the product’s title as the cell’s text.

Now, if you build and run your app in the Simulator, you should see the titles of the products in your store load
into the table view, like so…

iOS inventory list

Displaying product details

Go to the Main.storyboard file within Xcode and navigate to the Detail Scene and add a label for the product title, a label for the product price, and a label for the product description (you’ll also want to ensure that the number of lines property of the product description to zero, and set up some appropriate basic auto-layout constraints). You should end up with a storyboard scene that looks like this…

iOS product details

Then, in your DetailViewController.h file, add the following declarations

  @property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *descriptionLabel;
and go back to your Detail Scene in the Main.storyboard file to wire up the new outlets like so…

iOS product view

Then, in your DetailViewController.m file, replace the implementation of the configureView method with the following…

  if (self.detailItem) {
  // Set the item title from the detailItem dictionary's 'title' key
  self.titleLabel.text = [self.detailItem valueForKey:@"title"];
  
  // Set the formatted price with tax by looking at the key path in the detailItem dictionary
  self.priceLabel.text = [self.detailItem valueForKeyPath:@"price.data.formatted.with_tax"];
  
  // Set the item description from the detailItem dictionary's 'description' key
  self.descriptionLabel.text = [self.detailItem valueForKey:@"description"];
}

As you can see, this code gets the values from the detailItem dictionary (which contains the product information as a dictionary), passed to the detail view instance from the master table view objects array), and sets the relevant label text string values to the values from the product dictionary.

If you run the app now in the simulator and tap on a product name, you should see the following product detail view, with the correct product title, price, and description loaded in…

iOS product data

Adding a product to the cart

Now we’ve got the product details loading in, we'll look at adding the products to the cart. First, we’ll add the button to allow us to do this - go to the Detail Scene within Main.storyboard and add a button (with some appropriate constraints), so you end up with a scene like below…

iOS add product to cart

Then, go to the DetailViewController.h file and declare a method -(IBAction)addToCart:(id)sender;Go back to the Main.storyboard file and wire it up to the Touch Down event on the Add to cart button.

Go back to the Detail ViewController.h file and add #import <Moltin/Moltin.h> at the top, with the other import statements.

Once you have this in place, go to DetailViewController.m, and we can begin the implementation. Your addToCart method implementation in the .m file needs to look like this…

  -(IBAction)addToCart:(id)sender {
  // Get the current product's ID string from the detailItem product info dictionary...
  NSString *productId = [self.detailItem valueForKey:@"id"];
  
  [[[Moltin sharedInstance] cart] insertItemWithId:productId quantity:1 andModifiersOrNil:nil success:^(NSDictionary *response) {
// Added to cart!
// We'll show a UIAlertController to tell the user what we've done...
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Added to cart!" message:@"Added item ot cart!" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okayButton = [UIAlertAction actionWithTitle:@"Okay" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:okayButton];
[self presentViewController:alert animated:YES completion:nil];

  } failure:^(NSDictionary *response, NSError *error) {
// Something went wrong...
NSLog(@"Could not add to cart - error = %@", error);
  }];   
}

Now, if you run the app and add an item from your store to the cart, you should see this success message…

iOS cart

So, items can now be viewed and added to the cart - next stage, checkout!

The checkout process

Now that we’ve got items added to the cart successfully, let’s look at how to implement checkout with the Moltin SDK.

In your production iOS apps, you’ll be offering beautiful checkout interfaces where users can enter their details elegantly (you can see an example of what we suggest in our iOS Example App project on GitHub here), but in this example, we’re going to hard-code the checkout details into the app to keep the tutorial as easy to follow as possible.

First, we’ll add a checkout button to the corner of the master product list. To do this, go to
your MasterViewController.m file and add the following to your viewDidLoad method…

  UIBarButtonItem *checkoutItem = [[UIBarButtonItem alloc] initWithTitle:@"Checkout!" style:UIBarButtonItemStylePlain target:self action:@selector(checkout)];
    self.navigationItem.rightBarButtonItem = checkoutItem;

This adds a Checkout! button to the righthand side of the top navigation bar on the master product list, that calls the checkout method when tapped. Now, we’ll go and implement that checkout method. In the MasterViewController.m file, you’ll need to add the following method…

  -(void)checkout {
  // Perform the checkout (with hard-coded user data for tutorial sake)
  // Define the order parameters (hardcoded in this example)
  
  // You'll likely always want to hard code 'gateway' so that it matches your store's payment gateway slug.
  NSDictionary *orderParameters = @{
                              @"customer" : @{ @"first_name" : @"Jon",
                                               @"first_name" : @"Doe",
                                               @"email" : @"jon.doe@gmail.com"
                                               },
                              @"shipping" : @"free-shipping",
                              @"gateway"  : @"dummy",
                              @"bill_to"  : @{ @"first_name" : @"Jon",
                                               @"last_name" :  @"Doe",
                                               @"address_1" :  @"123 Sunny Street",
                                               @"address_2" :  @"Sunnycreek",
                                               @"city" :       @"Sunnyvale",
                                               @"county" :     @"California",
                                               @"country" :    @"US",
                                               @"postcode" :   @"CA94040",
                                               @"phone" :      @"6507123124"
                                               },
                              @"ship_to"  : @"bill_to"
                              };
  
  [[Moltin sharedInstance].cart orderWithParameters:orderParameters
                                      success:^(NSDictionary *response) {
// Checkout order succeeded! Let's go on to payment too...
// Extract the Order ID so that it can be used for payment too...
NSString *orderId = [response valueForKeyPath:@"result.id"];
                      
// These payment parameters would contain the card details entered by the user in the checkout UI flow...
NSDictionary *paymentParameters = @{ @"data" : @{
                                     @"number"       : @"4242424242424242",
                                     @"expiry_month" : @"02",
                                     @"expiry_year"  : @"2017",
                                     @"cvv"          : @"123"
                                     }
                                    };
                                          
  [[Moltin sharedInstance].checkout paymentWithMethod:@"purchase" order:orderId parameters:paymentParameters success:^(NSDictionary *response) {
    // Payment success too!
    // We'll show a UIAlertController to tell the user they're done.
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Order complete!" message:@"Order complete and your payment   has been processed - thanks for shopping with us!" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okayButton = [UIAlertAction actionWithTitle:@"Okay" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:okayButton];
    [self presentViewController:alert animated:YES completion:nil];  
    
  // In a production store app, this would be a great time to show a receipt...
       
  } failure:^(NSDictionary *response, NSError *error) {
// Something went wrong with the payment...
NSLog(@"Payment error: %@", error);
  }];
 
  } failure:^(NSDictionary *response, NSError *error) {
    // Something went wrong with the order...
    NSLog(@"Order error: %@", error);  
  }];
}

As you can see in this checkout method, we’re creating dictionaries containing user order data and payment data (hard-coded in this example, but in real life production apps this is the data you’d be getting the user to enter in a series of text fields), then calling the orderWithParameters method of the Moltin SDK to place the order, passing in the user’s contact, shipping and billing details; once that succeeded, we can then call the paymentWithMethod method, passing in the user’s payment details. Once the payment has succeeded, the order is complete!

When you run the app in the simulator now, after adding an item to the cart and tapping Checkout, you should see the following success message…

iOS checkout

Congratulations - you’ve just built your first iOS eCommerce app with Moltin! For a more thorough example that includes cart, collections, checkout flow and Apple Pay, why not take a look at our Example Objective-C app, or our Example Swift app - both on GitHub.

You can check out and download the source code for this tutorial project on GitHub here.

Let's build something amazing with Moltin