<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sami Korpela on Medium]]></title>
        <description><![CDATA[Stories by Sami Korpela on Medium]]></description>
        <link>https://medium.com/@skipadu?source=rss-85d95686c1c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RR9AMizD0osAuyEC-FMcCQ.jpeg</url>
            <title>Stories by Sami Korpela on Medium</title>
            <link>https://medium.com/@skipadu?source=rss-85d95686c1c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:50:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@skipadu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Realm and Charts with Swift 3 in iOS 10]]></title>
            <link>https://medium.com/@skipadu/using-realm-and-charts-with-swift-3-in-ios-10-40c42e3838c0?source=rss-85d95686c1c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/40c42e3838c0</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[realmswift]]></category>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Sami Korpela]]></dc:creator>
            <pubDate>Tue, 11 Oct 2016 17:44:10 GMT</pubDate>
            <atom:updated>2017-01-07T14:48:56.364Z</atom:updated>
            <content:encoded><![CDATA[<p>I have had few challenges when I was reading some tutorials of how to use Realm and Charts together. Mostly because all the tutorials that I have found was for Swift 2 and older versions of Realm and/or Charts.</p><p>So I decided to make a simple example project on GitHub and write down the steps taken. This is for me to remember better and hopefully helping someone else with the same problem.</p><h4>About this tutorial</h4><p>This tutorial starts from the beginning of making new project and it assumes that the reader has little knowledge already from the Xcode and Swift.</p><p>In this example we make simple app where you calculate visitors and add the current count to database with a date by pressing button. Then it will be shown in the chart right away.</p><h4>Software used in this tutorial</h4><p>Here is the list of the used software I used in this tutorial. If you don’t already have CocoaPods installed on your machine, please look the installation guide from below, because it’s needed to follow this guide.</p><ul><li>Xcode 8.0 (8A218a)</li><li><a href="https://guides.cocoapods.org/using/getting-started.html#what-is-cocoapods">CocoaPods</a> (1.0.1) (<em> </em><a href="https://guides.cocoapods.org/using/getting-started.html#installation"><em>installation guide</em></a><em> </em>)</li><li><a href="https://github.com/realm/realm-cocoa">RealmSwift</a> (2.0.2)</li><li><a href="https://github.com/danielgindi/Charts">Charts</a> (3.0.1)</li><li>Your favorite text editor for editing Podfile ( I use <a href="https://www.sublimetext.com/">Sublime Text</a> )</li></ul><h3>Creating new project</h3><p>Start your Xcode and create new Xcode project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*qXs1_i-y0-hD8jafhfdtgw.png" /><figcaption>Create a new Xcode project</figcaption></figure><p>Then choose <strong>Single View Application</strong> and hit <strong>Next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*m8cr0dnrkFRDd6bchBcAAQ.png" /><figcaption>Choose Single View Application -template</figcaption></figure><p>Now we set the options to our project. You can use whatever name you want to be <strong>Product name</strong>, <strong>Organization Name</strong> and <strong>Organization identifier</strong>. When you have filled the data as you desire, hit the <strong>Next</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*gfOpYi9Eepg99eaz5BxUuA.png" /><figcaption>Fill the fields with the information you like</figcaption></figure><p>Next you are going to select the location for the project to be stored on your device. In this example I have selected the Desktop. Check <strong>Source Control</strong> if you like to make Git repository for the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*D7RMjiRyJGfB4O4EecS8WQ.png" /><figcaption>Select location for your project to be stored</figcaption></figure><p>After this your project is created and you are shown a similar Xcode like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUfqiK-HJUUESiwgbpHMtw.png" /><figcaption>Project is created</figcaption></figure><p>Now close the Xcode.</p><h3>Using CocoaPods</h3><p>Next we are going to setup the CocoaPods for project. For this you have to open the <strong>Terminal</strong> and go to the folder you created the project. Because we did save the project in this tutorial to desktop we will write like this to the Terminal:</p><pre><strong>cd Desktop/RealmAndCharts-example/RealmAndCharts-example/</strong></pre><p>Now you are in the correct folder and we are ready to set up the CocoaPods. So write following command to Terminal.</p><pre><strong>pod init</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*ClqFFuOYGtW1qUj2ZYBivw.png" /><figcaption>Set up the CocoaPods in your project folder by <strong><em>pod init</em></strong></figcaption></figure><p>CocoaPods will generate a file named <strong>Podfile</strong>. Open it in your favorite text editor. It’s contents will look like in the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTyyySSXFjQTHNoett_9GA.png" /><figcaption>Podfile without any change</figcaption></figure><p>You need to add following pod, <strong>Charts</strong>, to the file.</p><pre><strong>pod &#39;Charts&#39;, &#39;~&gt; 3.0.1&#39;</strong></pre><p>After that you want to add the RealmSwift to your podfile. So add following:</p><pre><strong>pod &#39;RealmSwift&#39;, &#39;~&gt; 2.0.2&#39;</strong></pre><p>First is the name and then the version of it. It’s recommended to specify the pod version like this if possible when adding, so later when adding new pods it doesn’t get updated automatically to newest by you not knowing it. And sometimes this might get you to pulling hair out of your head, because you are not sure why it happened.</p><p>And you should also add the following to the end of your podfile. It’s from the <a href="https://realm.io/docs/swift/latest/#installation">Realm’s installation guide</a>.</p><pre><strong>post_install do |installer|<br>    installer.pods_project.targets.each do |target|<br>      target.build_configurations.each do |config|<br>        config.build_settings[&#39;SWIFT_VERSION&#39;] = &#39;3.0&#39;<br>      end<br>    end<br>  end</strong></pre><p>It will update the Swift version to 3.0 if needed in the code. And then Xcode shouldn’t nag for you to convert syntax to Swift 3 when you start it up next time.</p><p>Your podfile should now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*eMxTIv_MALu-CcR9o1-VAg.png" /><figcaption>Needed pods added to Podfile</figcaption></figure><p>Then save the podfile and go to <strong>Terminal</strong> and write:</p><pre><strong>pod install</strong></pre><p>It will download the pods, installs them and make other needed changes. But you may experience error like this if your pods are not up to date:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*3rKlnC7_5vrlxZOkj-lrYw.png" /><figcaption>Error while trying <strong>pod install</strong></figcaption></figure><p>Then do as the error suggests, write:</p><pre><strong>pod repo update</strong></pre><p>It will then update to repository of CocoaPods and may take awhile. After it completes, try the <strong>pod install</strong> again. And now it should download pods nicely without a hitch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*QiBY5FLZtRx2ZdUKuImc8A.png" /><figcaption><strong>pod install</strong> going right</figcaption></figure><p>As it says in the <strong>Terminal</strong> CocoaPods have made a new file, <strong>RealmAndCharts-example.xcworkspace</strong>. You should now open project with that file from now on.</p><h3>Open the workspace in Xcode</h3><h4>Get rid of warnings</h4><p>After you opened the workspace in Xcode, you notice that it has warning. Click it on the upper right corner, marked with red arrow in picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YU_g8ByHJ-IABfJ4a0o7yw.png" /><figcaption>Click the <strong>Warning</strong> icon</figcaption></figure><p>You are then show a similar dialog like below, hit <strong>Perform Changes</strong> -button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*TH3fNQuN2sJw4PYsgba4CA.png" /></figure><p>Then it does show following dialog if you have uncommitted changes in project, hit <strong>Continue</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*OwmRBLaaJksrHxUtWyS7lw.png" /></figure><p>After this is still might show same kind of warning icon, so click it again and now first dialog will differ a little from first one. Proceed like with the first warning and then you should no longer have warnings on your workspace regarding this same.</p><p>Then open the <strong>Main.storyboard</strong>.</p><h4>Adding components to layout</h4><p>You need a way to add data to Realm database, so let’s start by adding <strong>textfield</strong> for value to be stored and a <strong>button</strong> which saves the item to database. You can add them as you like, which you see fits the best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*_uCrQVmusfdSphFHyN0nAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*8XobGge5nm9tp03zSsmTEg.png" /></figure><p>Choose the textfield and change <strong>Keyboard type </strong>to be <strong><em>Number pad</em></strong> from <strong>Attributes inspector. </strong>Then user can only enter numbers to our field, which suits our purpose more than better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*ykW8XuRaxjCBsJ92NL3ZQw.png" /><figcaption>Changing <strong>Keyboard Type</strong> to Number Pad</figcaption></figure><p>You should add also <strong>View</strong> to your storyboard. That will be used to show the chart with the example data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*r_z0USjQWCQMndDgJfoqKA.png" /><figcaption>Choose <strong>View </strong>from Object Library</figcaption></figure><p>While you have selected the <strong>View </strong>component, go to <strong>Identity Inspector </strong>page and change the <strong>Class</strong> to be <strong><em>BarChartView</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*lSweku68iBksdU69uVfjvw.png" /><figcaption>Choose the <strong>BarChartView</strong> in Identity Inspector for the View</figcaption></figure><p>This is how I put those to layout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*LEsx_mqh1ugiRfMDNpS-7Q.png" /><figcaption>Example of laying out the components</figcaption></figure><h4>Creating outlets</h4><p>Now you need to make the outlet for the textfield and view. First show the assistant editor by pressing the button for it in the top-right corner of Xcode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*GLyj2lI43mcW6oxDl1eaFg.png" /><figcaption><strong>Show the Assistant editor</strong> -button</figcaption></figure><p>Then press <strong>Control</strong> button and drag from the <strong>textfield</strong> to code. When you release the mouse button, you get the dialog. Name it <strong><em>tfValue</em></strong> and hit <strong>Connect</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*9_a2bksIycXn_H4xpnioTg.png" /></figure><p>Then do also the outlet for the <strong>View</strong> to the code. Name it <strong><em>barView. </em></strong>It will show error for the outlet because we have not imported the <strong>Charts</strong> pod yet.</p><p>Add the import clause just under the UIKit, so then your imports are like this:</p><pre>import UIKit<br><strong>import Charts</strong></pre><p>And press <strong>Command + B</strong> to build the workspace to get rid of the error.</p><h4>Remember to connect the button</h4><p>You need to make the button work, so create action for it. It is almost like doing outlet, but choosing <strong><em>Action</em></strong> from the dropdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*OSKP-6JnVQXZBMLr_9MjAA.png" /><figcaption>Creating action for the button</figcaption></figure><p>Then we are going to make it do some work for you.</p><h4>Taking RealmSwift in to equation</h4><p>You are going to need an class which you are saving to Realm database. In this example we make a class, <strong><em>VisitorCount,</em></strong><em> for that purpose.</em></p><p>So make a new Swift file and write the code to look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*UVClP11AQu1AtF2VoKs4lw.png" /><figcaption><strong>VisitorCount </strong>class for Realm</figcaption></figure><p>It’s superclass is Realm’s <a href="https://realm.io/docs/swift/latest/api/Classes/Object.html"><strong>Object</strong></a> and then Realm knows how to store it in the database. In this example we only add two fields for it; date for the time of record and field for the visitor count value.</p><pre><strong>dynamic var date: Date = Date()<br>dynamic var count: Int = Int(0)</strong></pre><p>Then you should told somehow to this object to save it to database. This can be done also in many other ways, but in this example we do it this way.</p><pre><strong>func save() {<br>  do {<br>    let realm = try Realm()<br>    try realm.write {<br>      realm.add(self)<br>    }<br>  } catch let error as NSError {<br>   fatalError(error.localizedDescription)<br>  }<br>}</strong></pre><p>You will use this method little later when adding the visitor count to database by clicking the <strong><em>Add</em></strong> button. It will open the connection to Realm and write this object to it. If any error arises, we catch it.</p><p>Now when you have the VisitorCount class ready, let’s use it when tapping the button.</p><h4>Action for the button</h4><p>Open the <strong>ViewController.swift</strong> and then go to the function you created for the button. Write some code, so it will look like this:</p><pre>@IBAction func btnAddTapped(_ sender: AnyObject) {<br><strong>  if let value = tfValue.text , value != &quot;&quot; {<br>    let visitorCount = VisitorCount()<br>     visitorCount.count = (NumberFormatter().number(from: value)?.intValue)!<br>     visitorCount.save()<br>     tfValue.text = &quot;&quot;<br>  }</strong><br>}</pre><p>We are checking that the textfield value is not empty. And if it’s not empty, we create new <strong>VisitorCount</strong> object and parse the value currently as string to be integer value. Then we save it to Realm database and clear the textfield to be ready for next value.</p><h3>Showing data on chart</h3><p>We now have a way to add visitor counts to database, but we are not able to show them yet. So that will be our next step.</p><p>First, add import for RealmSwift, by adding it under existing imports. We need that soon and when adding the needed import now we don’t get the error of missing import. Of course you can write the code first, but then Xcode can’t assist you when writing code because it doesn’t know how.</p><pre><strong>import RealmSwift</strong></pre><p>In your <strong>viewDidLoad </strong>-function make call to a new function that we are going to do.</p><pre>override func viewDidLoad( {<br>  super.viewDidLoad()<br>  <strong>updateChartWithData()</strong><br>}</pre><p>Then we are going to create the function we are calling. It is used to update the data that is seen on chart.</p><pre><strong>func updateChartWithData() {<br>  var dataEntries: [BarChartDataEntry] = []<br>  let visitorCounts = getVisitorCountsFromDatabase()<br>  for i in 0..&lt;visitorCounts.count {<br>    let dataEntry = BarChartDataEntry(x: Double(i), y: Double(visitorCounts[i].count))<br>    dataEntries.append(dataEntry)<br>  }<br>  let chartDataSet = BarChartDataSet(values: dataEntries, label: &quot;Visitor count&quot;)<br>  let chartData = BarChartData(dataSet: chartDataSet)<br>  barView.data = chartData<br>}</strong></pre><p>And here is the other method which only fetches the database records and it’s used in the <strong>updateChartWithData</strong> -function.</p><pre><strong>func getVisitorCountsFromDatabase() -&gt; Results&lt;VisitorCount&gt; {<br>  do {<br>    let realm = try Realm()<br>    return realm.objects(VisitorCount.self)<br>  } catch let error as NSError {<br>    fatalError(error.localizedDescription)<br>    }<br>}</strong></pre><p>We also want to update the chart right away after we have added new visitor count, so let’s call the update function also from <strong>btnAddTapped</strong> -function:</p><pre>@IBAction func btnAddTapped(_ sender: AnyObject) {<br>  if let value = tfValue.text , value != “” {<br>    let visitorCount = VisitorCount()<br>    visitorCount.count = (NumberFormatter().number(from: value)?.intValue)!<br>    visitorCount.save()<br>    tfValue.text = “”<br>  }<br>  <strong>updateChartWithData()<br></strong>}</pre><h3>Trying the app for the first time</h3><p>Now when we should have all the functions ready, let’s start the app in the simulator and test it out. Hit <strong>Command + R</strong> to run it on your selected simulator. You then see the app like following. As you can see, there is the text <strong><em>Description Label</em></strong> on the lower right corner by default, we are not interested in that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*XtLJuwPVlzevExuo4gOu7A.png" /><figcaption>App launched for the first time</figcaption></figure><p>Now add visitor count to textfield and hit <strong>Add</strong>. I test it with number <strong><em>125</em></strong>. And then it will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*f5tnv_t8MVt1d1aSKDSDrQ.png" /></figure><p>Congratulations for showing the first data in your chart! Now try adding more data if you like, so you can see how the chart will adjust itself. Here is my random visitor counts added:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*c3HcfdKb_CWOB3lme38Ipg.png" /></figure><p>But wait a moment! What in the world is in the X-axis? They are just double values but not the dates we want! That is because we haven’t used the date we added to <strong>VisitorCount</strong> object! We like to have it in following format, e.g: “HH:mm.ss” = 18:34.20. So let’s make it happen.</p><h3>Setting date in X-axis</h3><p>First, we need to present delegate where are telling different implementation than what it is doing by default.</p><p>Just under the outlets you did for textfield and value, we add this delegate variable.</p><pre>class ViewController: UIViewController {<br>  @IBOutlet weak var tfValue: UITextField!<br>  @IBOutlet weak var barView: BarChartView!<br>  <br>  <strong>weak var axisFormatDelegate: IAxisValueFormatter?</strong></pre><p>Then on your <strong>viewDidLoad</strong> we need to tell to delegate that the implementation is in this class, <strong>ViewController.swift</strong>.</p><pre>override func viewDidLoad() {<br>  super.viewDidLoad()<br>  <strong>axisFormatDelegate = self</strong><br>  <br>  updateChartWithData()<br>}</pre><p>And we need to change the current way of setting the X-axis’ value. So head to <strong>updateChartWithData()</strong> -function and make few changes in it.</p><p>Because Charts seems to like to have it’s X-axis value as <strong>Double</strong>, we need to make our date to be compatible with it. We do this by making <strong>TimeInterval</strong> from the date and set that to X-value.</p><p>Then we also set the custom formatter to our X-axis, which we are implementing little later. This will tell chart how to show the data in X-axis.</p><p>It should look like this after the modification:</p><pre>func updateChartWithData() {<br>  var dataEntries: [BarChartDataEntry] = []<br>  <br>  let visitorCounts = getVisitorCountsFromDatabase()<br>  <br>  for i in 0..&lt;visitorCounts.count {<br>    <strong>let timeIntervalForDate: TimeInterval = visitorCounts[i].date.timeIntervalSince1970<br>    let dataEntry = BarChartDataEntry(x: Double(timeIntervalForDate), y: Double(visitorCounts[i].count))</strong><br>    dataEntries.append(dataEntry)<br>  }<br>  let chartDataSet = BarChartDataSet(values: dataEntries, label: &quot;Visitor count&quot;)<br>  let chartData = BarChartData(dataSet: chartDataSet)<br>  barView.data = chartData<br>  <br><strong>  let xaxis = barView.xAxis<br>  xaxis.valueFormatter = axisFormatDelegate</strong><br>}</pre><p>Then go to end of the whole file and outside the braces, we make an extension for <strong>ViewController</strong>, where we do implement for <strong>IAxisValueFormatter. </strong>It will be used to show dates in X-axis.</p><p>Here we are making the opposite than we did before with the date; now we convert it back to date from the <strong>Double</strong> format. Then it’s easier to format as string when using <strong>DateFormatter</strong>.</p><pre>// MARK: axisFormatDelegate<br><strong>extension ViewController: IAxisValueFormatter {<br>  <br>  func stringForValue(_ value: Double, axis: AxisBase?) -&gt; String {<br>    let dateFormatter = DateFormatter()<br>    dateFormatter.dateFormat = “HH:mm.ss”<br>    return dateFormatter.string(from: Date(timeIntervalSince1970: value))<br>  }</strong></pre><pre><strong>}</strong></pre><p>After you have wrote the needed code, it’s time to run the app once again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*2RMapE9AMsV5XxJEVS1uPA.png" /><figcaption>X-axis now has dates</figcaption></figure><p>Now our app has dates in the X-axis. So we are done for now.</p><h3>Final words and what to do next</h3><p>Now you should have little more knowledge how to use Charts and RealmSwift in your project. You can learn more about those on their own page and expand the functionality of the example app.</p><h4>Here is few ideas what to expand / change</h4><ul><li>Add ability to remove data</li><li>Change formatting of dates on X-axis</li><li>Change colors in chart</li><li>Change to different kind of chart (LineChart maybe?)</li><li>Change the <strong>Description label</strong> to your own liking</li></ul><h3>Sources</h3><h4>Here is the link to the source code that was written in this tutorial</h4><ul><li><a href="https://github.com/skipadu/RealmAndCharts-example">https://github.com/skipadu/RealmAndCharts-example</a></li></ul><h4>Here are the sources that I used to gather the information.</h4><ul><li><a href="https://guides.cocoapods.org/">CocoaPods Guides</a></li><li><a href="https://www.appcoda.com/ios-charts-api-tutorial/">How to Use iOS Charts API to Create Beautiful Charts in Swift — Joyce Echessa</a></li></ul><h3>Thanks for reading!</h3><p><strong>Updated</strong> 20th October 2016: Fixed quotation marks on the Podfile. Medium seems to have changed them automatically when copy-pasting from file.</p><p><strong>Updated</strong> 7th January 2017: Updated the pod file configuration for Charts. No more need to tell certain branch like previously.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40c42e3838c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>