Using Realm and Charts with Swift 3 in iOS 10

Sami Korpela
Oct 11, 2016 · 12 min read

About this tutorial

Software used in this tutorial

Creating new project

Create a new Xcode project
Choose Single View Application -template
Fill the fields with the information you like
Select location for your project to be stored
Project is created

Using CocoaPods

cd Desktop/RealmAndCharts-example/RealmAndCharts-example/
pod init
Set up the CocoaPods in your project folder by pod init
Podfile without any change
pod 'Charts', '~> 3.0.1'
pod 'RealmSwift', '~> 2.0.2'
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['SWIFT_VERSION'] = '3.0'
end
end
end
Needed pods added to Podfile
pod install
Error while trying pod install
pod repo update
pod install going right

Open the workspace in Xcode

Get rid of warnings

Click the Warning icon

Adding components to layout

Changing Keyboard Type to Number Pad
Choose View from Object Library
Choose the BarChartView in Identity Inspector for the View
Example of laying out the components

Creating outlets

Show the Assistant editor -button
import UIKit
import Charts

Remember to connect the button

Creating action for the button

Taking RealmSwift in to equation

VisitorCount class for Realm
dynamic var date: Date = Date()
dynamic var count: Int = Int(0)
func save() {
do {
let realm = try Realm()
try realm.write {
realm.add(self)
}
} catch let error as NSError {
fatalError(error.localizedDescription)
}
}

Action for the button

@IBAction func btnAddTapped(_ sender: AnyObject) {
if let value = tfValue.text , value != "" {
let visitorCount = VisitorCount()
visitorCount.count = (NumberFormatter().number(from: value)?.intValue)!
visitorCount.save()
tfValue.text = ""
}

}

Showing data on chart

import RealmSwift
override func viewDidLoad( {
super.viewDidLoad()
updateChartWithData()
}
func updateChartWithData() {
var dataEntries: [BarChartDataEntry] = []
let visitorCounts = getVisitorCountsFromDatabase()
for i in 0..<visitorCounts.count {
let dataEntry = BarChartDataEntry(x: Double(i), y: Double(visitorCounts[i].count))
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Visitor count")
let chartData = BarChartData(dataSet: chartDataSet)
barView.data = chartData
}
func getVisitorCountsFromDatabase() -> Results<VisitorCount> {
do {
let realm = try Realm()
return realm.objects(VisitorCount.self)
} catch let error as NSError {
fatalError(error.localizedDescription)
}
}
@IBAction func btnAddTapped(_ sender: AnyObject) {
if let value = tfValue.text , value != “” {
let visitorCount = VisitorCount()
visitorCount.count = (NumberFormatter().number(from: value)?.intValue)!
visitorCount.save()
tfValue.text = “”
}
updateChartWithData()
}

Trying the app for the first time

App launched for the first time

Setting date in X-axis

class ViewController: UIViewController {
@IBOutlet weak var tfValue: UITextField!
@IBOutlet weak var barView: BarChartView!

weak var axisFormatDelegate: IAxisValueFormatter?
override func viewDidLoad() {
super.viewDidLoad()
axisFormatDelegate = self

updateChartWithData()
}
func updateChartWithData() {
var dataEntries: [BarChartDataEntry] = []

let visitorCounts = getVisitorCountsFromDatabase()

for i in 0..<visitorCounts.count {
let timeIntervalForDate: TimeInterval = visitorCounts[i].date.timeIntervalSince1970
let dataEntry = BarChartDataEntry(x: Double(timeIntervalForDate), y: Double(visitorCounts[i].count))

dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Visitor count")
let chartData = BarChartData(dataSet: chartDataSet)
barView.data = chartData

let xaxis = barView.xAxis
xaxis.valueFormatter = axisFormatDelegate

}
// MARK: axisFormatDelegate
extension ViewController: IAxisValueFormatter {

func stringForValue(_ value: Double, axis: AxisBase?) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = “HH:mm.ss”
return dateFormatter.string(from: Date(timeIntervalSince1970: value))
}
}
X-axis now has dates

Final words and what to do next

Here is few ideas what to expand / change

Sources

Here is the link to the source code that was written in this tutorial

Here are the sources that I used to gather the information.

Thanks for reading!

Sami Korpela

Written by

Coding, drawing, gaming.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade