Creating a mobile store: part 2

Dylan Mckee profile picture
Last updated: 03 Oct 2018

This information is specific to the deprecated version one. For more up-to-date details, see: our Developer Portal.

In this second tutorial, we’ll be taking you through the process of creating your first iOS mobile store app with Moltin in Swift.

The Moltin iOS SDK offers the perfect solution for mobile developers looking to incorporate eCommerce into their Swift app using a native iOS SDK, with no writing of backend code or server administration required - Moltin handle the backend, giving you the power to concentrate on writing a great app using our modern Swift 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. Also, uncomment the line use_frameworks! to make CocoaPods Swift compatible. Then, run the pod install command in Terminal, open up the created .xcworkspace in Xcode.

Once you’ve done this, go to File > New > File, then select Header File, call it BridgingHeader, then, go to your target’s Build Settings, search for Objective-C Bridging Header, and then type BridgingHeader.h; your setup should now look like the one shown in the screenshot below…

iOS setup

Then, head to BridgingHeader.h and add the line #import - your bridging header file should end up looking like the one below…

iOS bridging header

Now, you’re ready to start using our iOS SDK in your Swift code!

Next, 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.

Setting up the SDK

Head to the MasterViewController.swift file in your Xcode project and import the Moltin SDK by adding the line import Moltin at the top of the file. Then, in the viewDidLoad function 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 MasterViewController.swift file, let’s get the products from the Moltin API by adding the following code to your viewDidLoad function:

  Moltin.sharedInstance().product.listingWithParameters(nil, success: { (response) -> Void in
    // The array of products is at the "result" key
    self.objects = response["result"]! as! [AnyObject]
    
    // Reload the table view that'll be used to display the products...
    self.tableView.reloadData()
    
}, failure: { (response, error) -> Void in
    print("Something went wrong! \(error)")
})

This code uses the SDKs listingWithParameters method, with empty parameters, to return every product in your store from the Moltin API, which 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 function with:

  let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

let object = objects[indexPath.row] as! [String: AnyObject] 
cell.textLabel!.text = object["title"] as? String
  
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…

Swift product list

Finally, in your MasterViewController.swift file, replace the contents of the prepareForSegue function with the following code…

  if segue.identifier == "showDetail" {
    if let indexPath = self.tableView.indexPathForSelectedRow {
  let object = objects[indexPath.row] as! NSDictionary
  let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
  controller.detailItem = object
  controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
  controller.navigationItem.leftItemsSupplementBackButton = true
    }
}

This allows the product you select to be passed to the detail view (that you’ll be creating next) as an NSDictionary object.

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…

Swift product storyboard

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

  @IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!

and go back to your Detail Scene in the Main.storyboard file to wire up the new outlets like so…

Swift product detail scene

Then, replace the implementation of the configureView function with the following…

  if let detail = self.detailItem as? NSDictionary {
   // Set the item title from the detailItem dictionary's 'title' key
   if let title = detail.valueForKey("title") as? String {
 titleLabel?.text = title
 self.title = titleLabel?.text
   }

   // Set the formatted price with tax by looking at the key path in the detailItem dictionary
   if let price = detail.valueForKeyPath("price.data.formatted.with_tax") as? String {
 priceLabel?.text = price
   }
  
   // Set the item description from the detailItem dictionary's 'description' key
   if let description = detail.valueForKey("description") as? String {
 descriptionLabel?.text = 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…

Swift product view

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…

Swift add to chart

Head to the Detail ViewController.swift file and add import Moltin at the top.

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

  @IBAction func addToCart(sender: AnyObject) {
    // Get the current product's ID string from the detailItem product info dictionary...
    let productId: String = self.detailItem?.valueForKey("id") as! String
   
    Moltin.sharedInstance().cart.insertItemWithId(productId, quantity: 1, andModifiersOrNil: nil, success: { (response) -> Void in
      // Added to cart!
      // We'll show a UIAlertController to tell the user what we've done...
      let alert = UIAlertController(title: "Added to cart!", message: "Added item to cart!", preferredStyle: UIAlertControllerStyle.Alert)
      alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))
      self.presentViewController(alert, animated: true, completion: nil)
  
  }, failure: { (response, error) -> Void in
      print("Something went wrong! \(error)")
    })
    
}

Then, go back to the Main.storyboard file and wire addToCart: up to the Touch Down event on the Add to cart button.

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

Swift cart success

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), 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.swift file and add the following to your viewDidLoad function...

  let checkoutButton = UIBarButtonItem(title: "Checkout!", style: UIBarButtonItemStyle.Plain, target: self, action: "checkout")
self.navigationItem.rightBarButtonItem = checkoutButton

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

  Moltin.sharedInstance().cart.orderWithParameters(orderParameters, success: { (response) -> Void in
  // Checkout order succeeded! Let's go on to payment too...
  print("Order succeeded: \(response)")
  
  // Extract the Order ID so that it can be used in payment too...
  let orderId = (response as NSDictionary).valueForKeyPath("result.id") as! String
  
  // These payment parameters would contain the card details entered by the user in the checkout UI flow...
  let paymentParameters = ["data": [
      "number":       "4242424242424242",
      "expiry_month": "02",
      "expiry_year":  "2017",
      "cvv":          "123"
      ]] as [NSObject: AnyObject]
  
  Moltin.sharedInstance().checkout.paymentWithMethod("purchase", order: orderId, parameters: paymentParameters, success: { (response) -> Void in
      // Payment successful...
      print("Payment successful: \(response)")
      
      // Payment success too!
      // We'll show a UIAlertController to tell the user they're done.
      let alert = UIAlertController(title: "Order complete!", message: "Order complete and your payment has been processed - thanks for shopping with us!", preferredStyle: UIAlertControllerStyle.Alert)
      alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))
      self.presentViewController(alert, animated: true, completion: nil)
      
      // In a production store app, this would be a great time to show a receipt...

      
      }, failure: { (response, error) -> Void in
          // Payment error
          print("Payment error: \(error)")
  })
  
  }, failure: { (response, error) -> Void in
      // Order failed
      print("Order error: \(error)")
    })
}

As you can see in this checkout function, 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…

Swift checkout success

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

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

Let's build something amazing with Moltin