Skip to content
This repository has been archived by the owner on Dec 3, 2019. It is now read-only.

Quick Start (Swift)

Nick Entin edited this page Aug 7, 2016 · 1 revision

In this walkthrough, we will set up a data source that provides access to all contacts from the user's address book that have a phone number. This walkthrough uses Swift, but there is also an Objective-C version available.

Setting Up the Data Provider

We will be using the Apple-provided Contacts framework as the source of our data. Ohana comes with a data provider that pulls from the address book, the OHCNContactsDataProvider.

let dataProvider = OHCNContactsDataProvider(delegate: self)

The data provider requires that we pass in a delegate conforming to the OHCNContactsDataProviderDelegate protocol. This delegate handles requesting authentication. We will request system authentication using one of the functions in the Contacts framework.

@available(iOS 9.0, *)
func dataProviderDidHitContactsAuthenticationChallenge(dataProvider: OHCNContactsDataProvider) {
    let store = CNContactStore()
    store.requestAccessForEntityType(.Contacts) { (granted, error) in
        if granted {
            dataProvider.loadContacts()
        }
    }
}

Setting Up the Post Processors

First, we will create an alphabetical sort post processor to sort our contacts by full name.

let alphabeticalSortProcessor = OHAlphabeticalSortPostProcessor(sortMode: .FullName)

Next, we will filter out any contacts that don't have a phone number.

let phoneNumberProcessor = OHRequiredFieldPostProcessor(fieldType:.PhoneNumber)

Setting Up the Data Source

We are now ready to set up our data source using the data provider and post processors that we have created.

let dataSource = OHContactsDataSource(dataProviders: NSOrderedSet(objects: dataProvider), postProcessors: NSOrderedSet(objects: alphabeticalSortProcessor, phoneNumberProcessor))

Now we'll add ourselves as an observer to the data source's ready signal so we can do something with the contacts when they're loaded.

dataSource.onContactsDataSourceReadySignal.addObserver(self, callback: { (self) in
    // do something with dataSource.contacts
})

Load Contacts

Now you're ready to start the loading process and get some contacts.

dataSource.loadContacts()