Blog / Development

Introducing the Kentico Cloud iOS SDK


by Martin Makarsky

Nov 16, 2017

Apple’s iOS is the world’s second most popular mobile operating system and it’s not a secret that iOS users spend much more on their devices compared to Android users. To ease the difficult process of implementing native apps for Apple’s ecosystem devices, we’ve created the Kentico Cloud SDK written in Swift.

Development for Apple’s Devices

For those not familiar with Apple’s development stack, there is a relatively new programming language called Swift. Swift was introduced in 2014, became open source a year later, and is now one of the fastest-growing programming languages out there. 

Swift is replacing its complicated counterpart Objective-C and, thanks to its similarity to modern languages like C#, Java, and JavaScript, it’s far easier to adopt. Apple provides a free integrated development environment called Xcode, so you can start programming within a couple of minutes. 

It has always been possible to create iOS apps with content from Kentico Cloud, but you had to deal with all the network communication, crafting queries, parsing JSON responses, mapping models, and much more on your own. 

But now we introduce Kentico Cloud Swift SDK, and in this blog post I’d like to show you how you can utilize it to deliver content for your iOS apps (as well as watchOS, OS X, and tvOS).

Features of the Kentico Cloud Swift SDK

The Kentico Cloud Swift SDK helps you with retrieving content, adding contacts, and tracking activities. There are several features you can use in your next project:

  • getting content items
  • getting content types
  • getting taxonomies
  • tracking activities
  • adding contacts

And the best thing? You don’t have to do all the difficult stuff like networking and object mapping—all this is done by the SDK itself. Let’s show you how to integrate SDK into a project and look at some basic usage.

Adding SDK into Your Project

The easiest way is installing the package via Cocoapods. Cocoapods is a dependency manager for Swift (and Objective-C)—a sort of counterpart to .NET’s NuGet or npm from the Javascript world. Just add pod to your podfile:

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


And run pod install. This command will add KenticoCloud SDK with all the necessary dependencies to your project.

Creating a Type Object

Mapping proprietary responses to strongly typed objects is one of the biggest and most boring parts of integrating with any third-party service. But most of the work is done by the SDK itself, so you just need to define what you want to store in your strongly typed object. 

For example, let’s say we want to get articles from Kentico Cloud—an article has a title (the Text element), an asset (the Asset element), and a postDate (the Date & Time element). We have two options here:

  • 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) {
    }
}


  • 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. If you need advanced mapping, see the documentation.

Getting and Using Items

In order to get items, you just need to create an instance of the DeliveryClient with your project Id and pass a query to the getItem/getItems methods. You have two options for creating a query:

  •  You can 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]


  •  For more advanced queries, you can craft a query on your own—the process for crafting queries is the same as in the Kentico Cloud Delivery documentation
let customQuery = "items?system.type=article&order=elements.post_date[desc]"


The last step is getting items from the Cloud and using them in your app. Requested items are returned to the completion handler. The Completion handler is just a simple callback which contains 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)
        }
    }
}

Single Items, Taxonomies, and Content Types

You can get a single item, multiple content types, and even taxonomies in a similar way. You can find more examples for getting these objects in our readme on GitHub.

Getting Modular Content

If your items contain 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)
	}
}

Debugging

While developing your apps, you may encounter strange behavior. To reduce this, you can pass a debug flag to the DeliveryClient object and you will be provided with additional messages in the output about your requests. You can add the optional enableDebugLogging flag:

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

Adding Contacts and Tracking Activities

Unlike traditional web analytics tools, Kentico Cloud tracks individual visitors and builds a complete picture of their activities. With this SDK, you can track your users even on iOS devices. You just need to start a session and track 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")

Where to Go from Here

You can find more information about features and usage of the SDK in our public GitHub repository. If you’re lacking any feature, do not hesitate to let us know in the discussion forums or create a new GitHub issue! We also have API reference documentation where you can find all our features. 

Kentico Cloud Swift SDK
on CocoaPods: CocoaPod version
platforms: platforms
build: build

Do you have any lingering questions? Get them answered in the forum below!