Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Understanding the Kentico Cloud iOS SDK

DZone's Guide to

Understanding the Kentico Cloud iOS SDK

The Kentico Cloud SDK for iOS provides functionality such as tracking activities and retrieving content. Learn how to add this SDK to your project in this tutorial.

· Mobile Zone ·
Free Resource

We know that Apple’s iOS is still currently the standout mobile operating system with its own set of advantages that Android or others have yet to beat. However, the process of implementing native applications for Apple’s ecosystem devices is quite tiresome.

Development for Apple’s Devices

Swift is considered one of the fastest growing programming languages; it is a lot easier to adapt as compared to similar modern languages like C#, Java, and JavaScript. Xcode is a free integrated development environment offered by Swift. This helps in starting the programming quickly.

Though it is quite possible to create iOS applications with content from Kentico Cloud, you may face difficulties such as making queries, mapping models, parsing JSON responses, and more.

Features of the Kentico Cloud Swift SDK

The Kentico Cloud Swift SDK helps users add contacts, track activities, and retrieve content. Some features which can be used in projects are

  • Getting content items

  • Getting content types

  • Getting taxonomies

  • Tracking activities

  • Adding contacts

The best part is that you do not have to bother with networking and object mapping. These are done in the SDK itself. 

How to Integrate the SDK Into a Project

1) Adding the SDK to Your Project

The best and simplest way to install the package is via Cocoapods, a dependency manager for Swift and Objective-C. It is a kind of counterpart to .NET’s NuGet or npm from the JavaScript world.

You just have to add the pod to your podfile:

target 'MyApp' do
  pod 'KenticoCloud', '~> 0.2'
end

Then, run pod install. This command will add the Kentico Cloud SDK with all the necessary dependencies to your project.

2) How to Create a Type Object

The mapping of proprietary responses to strongly typed objects is among the biggest and most bothersome parts of integrating with any third-party service. The good news is that most of the tasks are accomplished by the SDK itself. Now, you just have to define what exactly is to be stored in your strongly typed object.

This can be understood this way: if we want to get articles from Kentico Cloud, an article is comprised of a title, which is, of course, a Text element; an asset, which is an Asset element; and a postDate, which is the Date & Time element. This can be accomplished in two ways:

2.1. Using Strongly Typed Mapping Provided by Built-in Element Types

import ObjectMapper
import KenticoCloud

class Article: Mappable {
    var title: TextElement?
    var asset: AssetElement?
    var postDate: DateTimeElement?

    required init?(map: Map){
        let mapper = MapElement.init(map: map)
        title = mapper.map(elementName: "title", elementType: TextElement.self)
        asset = mapper.map(elementName: "teaser_image", elementType: AssetElement.self)
        postDate = mapper.map(elementName: "post_date", elementType: DateTimeElement.self)
    }

    func mapping(map: Map) {
    }
}


 2.2. Using Custom Mapping

import ObjectMapper

public class Article: Mappable {
    public var title: String?
    public var assetUrl: String?
    public var postDate: String?

    public required init?(map: Map){    
    }

    public func mapping(map: Map) {
        title <- map["elements.title.value"]
        assetUrl <- map["elements.teaser_image.value.0.url"]
        postDate <- map["elements.post_date.value"]
    }
}

Note: Both ways of mapping utilize the ObjectMapper framework. 


3) Getting and Using Items

You just need to create an instance of DeliveryClient with your project ID and pass a query to the getItem/getItems methods in order to get items. You can create a query in two ways:

3.1. Use a Strongly Typed Object Query

let typeQueryParameter = QueryParameter.init(parameterKey: QueryParameterKey.type, parameterValue: "article")
let languageQueryParameter = QueryParameter.init(parameterKey: QueryParameterKey.language, parameterValue: "es-ES")
let query= [typeQueryParameter, languageQueryParameter]

3.2. For more advanced queries, you can also write a query on your own. This is similar to the process of crafting queries the same as in the Kentico Cloud Delivery documentation:

let customQuery = "items?system.type=article&order=elements.post_date[desc]"

Finally, the last step is to get the items from the cloud and use them in your application. The requested items are returned to the completion handler and the completion handler is simply a callback which is comprised of received items.

client.getItems(modelType: Article.self, queryParameters: query) { (isSuccess, itemsResponse, error) in
    if isSuccess {
        if let articles = itemsResponse?.items {
            // use your articles here
        }
    } else {
        if let error = error {
            print(error)
        }
    }
}


4) Single Items, Taxonomies, and Content Types

You can also get a single item, multiple content types, and even the taxonomies. You can see a lot of examples of getting such objects on GitHub.

5) Getting Modular Content

If your items are comprised of some linked modular content, you can get this content directly from the deliveryResponse object. There is no need to make further server requests. You can get modular content with a codename of a certain type:

let client = DeliveryClient.init(projectId: "YOUR_PROJECT_ID")
client.getItem(modelType: Article.self, itemName: "on_roasts", completionHandler: { (isSuccess, itemResponse, error) in
    if isSuccess {
        let relatedArticle = itemResponse?.getModularContent(codename: "on_roasts", type: Article.self)
    }
}

6) Debugging

While developing an app, you may also face some weird behavior. You can minimize this by passing a debug flag to the DeliveryClient object. You will be provided with some additional messages in output about your requests. You can add the optional enableDebugLogging flag:

let deliveryClient = DeliveryClient.init(projectId: "YOUR_PROJECT_ID", enableDebugLogging = true)

7) Adding Contacts and Tracking Activities

Kentico Cloud tracks individual visitors and builds an entire picture of their activities, unlike traditional web analytics tools. This SDK helps you in tracking your users even on your iOS devices. You simply have to start a session and keep tracking the custom activity or add contacts:

let client = TrackingClient.init(projectId: "YOUR_PROJECT_ID")
client.startSession()
client.trackActivity(activityName: "madrid")
client.addContact(email: "martinkoklingacik@local.com")

Subscribe to Algoworks for more Kentico Blogs.

Topics:
mobile ,ios ,mobile app development ,sdk ,swift ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}