<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Objective C - AppCoda]]></title><description><![CDATA[AppCoda is one of the leading iOS programming communities. Our goal is to empower everyone to create apps through easy-to-understand tutorials. Learn by doing is the heart of our learning materials. ]]></description><link>https://www.appcoda.com/</link><image><url>https://www.appcoda.com/favicon.png</url><title>Objective C - AppCoda</title><link>https://www.appcoda.com/</link></image><generator>Ghost 5.83</generator><lastBuildDate>Tue, 19 May 2026 09:07:50 GMT</lastBuildDate><atom:link href="https://www.appcoda.com/tag/objective-c/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Debugging Out of Memory Issues: Catching Layout Feedback Loop with the Runtime Magic]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>Let&#x2019;s imagine this scenario: you&#x2019;ve got a successful app with a great number of daily users and 100% crash-free rate. You are happy and your life is amazing. But at some point you start seeing negative reviews coming to the App Store saying that it constantly</p>]]></description><link>https://www.appcoda.com/layout-feedback-loop/</link><guid isPermaLink="false">66612a0f166d3c03cf01148d</guid><category><![CDATA[iOS Programming]]></category><category><![CDATA[Objective C]]></category><dc:creator><![CDATA[Ruslan Serebriakov]]></dc:creator><pubDate>Thu, 10 Jan 2019 00:05:37 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2019/01/layout-feedback-loop.jpg" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://www.appcoda.com/content/images/wordpress/2019/01/layout-feedback-loop.jpg" alt="Debugging Out of Memory Issues: Catching Layout Feedback Loop with the Runtime Magic"><p>Let&#x2019;s imagine this scenario: you&#x2019;ve got a successful app with a great number of daily users and 100% crash-free rate. You are happy and your life is amazing. But at some point you start seeing negative reviews coming to the App Store saying that it constantly crashes. Checking Fabric doesn&#x2019;t help &#x2013; no new crashes have appeared. What could it be then?</p>
<p><em>The answer is OOM (Out of Memory) termination.</em></p>
<p>As you use RAM on an end user&#x2019;s device, the operating system can decide to reclaim that memory for other processes and terminate your app. We call this an Out of Memory termination. There might be various reasons for that:</p>
<ul>
<li>retain cycles;</li>
<li>race conditions;</li>
<li>abandoned threads;</li>
<li>deadlocks;</li>
<li>layout feedback loop.</li>
</ul>
<p>There are a lot of solutions provided by Apple to debug such kind of issues:</p>
<ul>
<li>Allocations and Leaks instruments for resolving retain cycles and <a href="https://developer.apple.com/videos/play/wwdc2015/230/?ref=appcoda.com">other types of leaks</a></li>
<li><a href="https://developer.apple.com/videos/play/wwdc2016/410/?ref=appcoda.com">Memory Debugger</a> which has been introduced in Xcode 8 and replaces some functionality from Allocations and Leaks instruments</li>
<li><a href="https://developer.apple.com/videos/play/wwdc2016/412/?ref=appcoda.com">Thread Sanitizers</a> help you find race conditions, abandoned threads or deadlocks</li>
</ul>
<h2>Layout Feedback Loop</h2>
<p>We are going to take a look into layout feedback loop. It is not a very frequent type of issue, but once you encountered it, it could give you a lot of headache.</p>
<blockquote><p>Layout feedback loops occur when your views are running their layout code, but part way through something causes them to start their layout pass again. This might be the result of one view changing the size of one of its superviews, or perhaps because you have an ambiguous layout. Either way, this problem manifests itself as your CPU maxing out and RAM usage steadily marching upwards, all because your views are running their layout code again and again without ever returning.</p>
<p>&#x2013; <a href="https://www.hackingwithswift.com/articles/59/debugging-auto-layout-feedback-loops?ref=appcoda.com">Paul Hudson from HackingWithSwift</a></p></blockquote>
<p>Luckily for us, in WWDC16 Apple spent the whole 15 minutes(!) introducing &#x201C;Layout Feedback Loop Debugger&#x201D; which helps identify the moment when a loop happens during debugging. This is just a symbolic breakpoint and the way it works is as simple as it gets: it counts the amount of times <code>layoutSubviews()</code> method on each view has been called in a single run loop iteration. Once it exceeds a certain threshold (let&#x2019;s say, 100), the app is going to stop at this breakpoint and print a nice log that helps you to find the root cause. <a href="https://www.hackingwithswift.com/articles/59/debugging-auto-layout-feedback-loops?ref=appcoda.com">Here</a> is a nice article shortly describing how to work with this debugger.</p>
<p>This works perfectly if you can reproduce the issue. But what if you have dozens of screens, hundreds of views but your App Store reviews only say: &#x201C;This app sucks, always crashing, never use it again!!!&#x201D; ? You wish you could bring all these people to your office and set up Layout Feedback Loop Debugger for them. While the first part is not entirely achievable due to GDPR, you can try to replicate <code>UIViewLayoutFeedbackLoopDebuggingThreshold</code> in production code.</p>
<p>Let&#x2019;s recall how this breakpoint works: it counts invocations of <code>layoutSubviews()</code> and sends an event when a certain threshold was exceeded in a single runloop iteration. Sounds easy, huh?</p>
<pre><code class="swift">class TrackableView: UIView {
    var counter: Int = 0

    override func layoutSubviews() {
        super.layoutSubviews()

        counter += 1;
        if (counter == 100) {
            YourAnalyticsFramework.event(name: &quot;loop&quot;)
        }
    }
}
</code></pre>
<p>This code works quite well for your view. But now you want to implement it on another views. You can, of course, create a subclass of <code>UIView</code>, implement it there and then inherit all the views in your project from it. And then do the same for <code>UITableView</code>, <code>UIScrollView</code>, <code>UIStackView</code>, and etc&#x2026;</p>
<p>You wish you could just inject this logic into whatever class you wanted without writing tons of duplicated code. And this is exactly what runtime programming allows you to do.</p>
<p>We are going to do the same thing &#x2013; create a subclass, override the <code>layoutSubviews()</code> method and count its invocations. The only difference is that all of this will be done at runtime instead of creating duplicated classes in your project.</p>
<p>Let&#x2019;s start simple &#x2013; we&#x2019;ll create our custom subclass and will change the original view&#x2019;s class to that new subclass:</p>
<pre><code class="swift">struct LayoutLoopHunter {

    struct RuntimeConstants {
        static let Prefix = &#x201C;runtime&#x201D;
    }

    static func setUp(for view: UIView, threshold: Int = 100, onLoop: @escaping () -&gt; ()) {
        // We create the name for our new class based on the prefix for our feature and the original class name
        let classFullName = &#x201C;\(RuntimeConstants.Prefix)_\(String(describing: view.self))&#x201D;
        let originalClass = type(of: view)

        if let trackableClass = objc_allocateClassPair(originalClass, classFullName, 0) {
            // This class hasn&#x2019;t been created during the current runtime session
            // We need to register our class and swap is with the original view&#x2019;s class
            objc_registerClassPair(trackableClass)
            object_setClass(view, trackableClass)
        } else if let trackableClass = NSClassFromString(classFullName) {
            // We&#x2019;ve previously allocated a class with the same name in this runtime session
            // We can get it from our raw string and swap with our view the same way
            object_setClass(view, trackableClass)
        }
    }
}
</code></pre>
<p><code>objc_allocateClassPair()</code>&#x2019;s documentation tells us when this method fails:</p>
<blockquote><p>The new class, or Nil if the class could not be created (for example, the desired name is already in use)&#x201D;.</p></blockquote>
<p>This means that you cannot have 2 classes with the same name. Our strategy is to have a single created-at-runtime class for a single view class. That&#x2019;s why we form the name for the new class by prefixing the original class name.</p>
<p>Now let&#x2019;s add a counter to our subclass. Theoretically there are two ways you can do this:</p>
<ol>
<li>Add a property which holds your counter.</li>
<li>Create an associated object for this class.</li>
</ol>
<p>But in face, <strong>only one way is valid</strong>. You can think of a property as something that is stored in the memory that has been allocated for your class whereas an associated object will be stored in a completely different place. Since the memory that was allocated for an existing object is fixed, the newly added property on our custom subclass is going to &#x201C;steal&#x201D; it from some other resource. It can lead to unexpected behaviors and hard-to-debug crashes (check <a href="https://stackoverflow.com/questions/3346427/object-setclass-to-bigger-class?ref=appcoda.com">here</a> for more info). But in case of using associated objects, they will be just stored in a hash table created during runtime, which is totally safe:</p>
<pre><code class="swift">static var CounterKey = &quot;_counter&quot;

...

objc_setAssociatedObject(trackableClass, &amp;RuntimeConstants.CounterKey, 0, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
</code></pre>
<p>Our new subclass is created, the counter is set to 0. Next, let&#x2019;s implement the new <code>layoutSubviews()</code> method and add it to our class:</p>
<pre><code>let layoutSubviews: @convention(block) (Any?) -&gt; () = { nullableSelf in
    guard let _self = nullableSelf else { return }

    if let counter = objc_getAssociatedObject(_self, &amp;RuntimeConstants.CounterKey) as? Int {
        if counter == threshold {
            onLoop()
        }

        objc_setAssociatedObject(trackableClass, &amp;RuntimeConstants.CounterKey, counter+1, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
}
let implementation = imp_implementationWithBlock(layoutSubviews)
class_addMethod(trackableClass, #selector(originalClass.layoutSubviews), implementation, &quot;v@:&quot;)
</code></pre>
<p>To understand what is actually going on above, let&#x2019;s take a look at this struct from <code>&lt;objc/runtime.h&gt;</code>:</p>
<pre><code class="objc">struct objc_method {
    SEL method_name;
    char *method_types;
    IMP method_imp;
}
</code></pre>
<p>Even though we don&#x2019;t use this struct directly in Swift anymore, it explains pretty clearly what a method actually consists of:</p>
<ul>
<li>Implementation, which is the exact function going to be executed when your method is called. It always has the receiver and message selector as its first two parameters.</li>
<li>Method types string contains the signature of your method. You can read more about its formatting <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html?ref=appcoda.com">here</a>, but in our case the string we need to specify is `&#x201D;v@:&#x201D;`. `v` stands for `void` as our return type, while `@` and `:` stand for the receiver and message selector respectively.</li>
<li>Selector is a key by which your method implementation will be looked up during runtime.</li>
</ul>
<p>You can imagine the witness table (it&#x2019;s also called dispatch table in other programming languages) as a simple dictionary data structure. The selector, then, would be your key and the implementation &#x2014; the value. What we are doing in this line:</p>
<pre><code>class_addMethod(trackableClass, #selector(originalClass.layoutSubviews), implementation, &quot;v@:&quot;)
</code></pre>
<p>is just assigning a new value for the key which corresponds to the <code>layoutSubviews()</code> method.</p>
<p>Straightforward as it gets. We get the counter, increase it by one. In case it exceeds our threshold, we send the analytics event with the name of the class and any payload we want.</p>
<p>Let&#x2019;s recall how we&#x2019;ve implemented and used the key for our associated object:</p>
<pre><code class="swift">static var CounterKey = &#x201C;_counter&#x201D;

...

objc_setAssociatedObject(trackableClass, &amp;RuntimeConstants.CounterKey, counter+1, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
</code></pre>
<p>Why did we use <code>var</code> for our static key property for the counter variable and passed it everywhere by reference? The answer is hidden in basics of Swift language &#x2013; Strings, like all the other value types, are passed by value. So, when you pass it to the closure, the string is being copied to a different address which would result in a completely different key in the associated objects table. The ampersand always ensures that the same address is given as value for the key parameter. Try the following code:</p>
<pre><code class="swift">func printAddress(_ string: UnsafeRawPointer) {
    print(&quot;\(string)&quot;)
}

let str = &quot;test&quot;

printAddress(str)
printAddress(str)
let closure = {
    printAddress(str)
    printAddress(str)
}
closure()
// The addresses for last two function calls will always be different
</code></pre>
<p>Passing the key by reference is always a good idea because sometimes, even if you are not using a closure, the address of your variable can still be changed due to memory management. For our example, if you run the above code for certain amount of times, you may be able to see different addresses even for the first two calls of <code>printAddress()</code>.</p>
<p>Let&#x2019;s go back to our runtime magic. There is an important thing which we haven&#x2019;t yet done in our new <code>layoutSubviews()</code> implementation. The thing that we normally do every time we override a method from an ancestor class &#x2013; call the superclass implementation. The documentation of <code>layoutSubviews()</code> says:</p>
<blockquote><p>The default implementation of this method does nothing on iOS 5.1 and earlier. Otherwise, the default implementation uses any constraints you have set to determine the size and position of any subviews.</p></blockquote>
<p>For avoiding any unexpected layout behaviour, we have to call the superclass&#x2019;s implementation. This will not be that straightforward as it usually is:</p>
<pre><code>let selector = #selector(originalClass.layoutSubviews)
let originalImpl = class_getMethodImplementation(originalClass, selector)

// @convention(c) tells Swift this is a bare function pointer (with no context object)
// All Obj-C method functions have the receiver and message as their first two parameters
// Therefore this denotes a method of type `() -&gt; Void`, which matches up with `layoutSubviews`
typealias ObjCVoidVoidFn = @convention(c) (Any, Selector) -&gt; Void
let originalLayoutSubviews = unsafeBitCast(originalImpl, to: ObjCVoidVoidFn.self)
originalLayoutSubviews(view, selector)
</code></pre>
<p>What is actually going on here is that instead of the usual way to call a method (i.e. perform the selector which is going to look up in the witness table for the implementation), we are retrieving the needed implementation ourselves and calling it directly from our code.</p>
<p>Let&#x2019;s see our implementation so far:</p>
<pre><code class="swift">static func setUp(for view: UIView, threshold: Int = 100, onLoop: @escaping () -&gt; ()) {
    // We create the name for our new class based on the prefix for our feature and the original class name
    let classFullName = &#x201C;\(RuntimeConstants.Prefix)_\(String(describing: view.self))&#x201D;
    let originalClass = type(of: view)

    if let trackableClass = objc_allocateClassPair(originalClass, classFullName, 0) {
        // This class hasn&#x2019;t been created during the current runtime session
        // We need to register our class and swap is with the original view&#x2019;s class
        objc_registerClassPair(trackableClass)
        object_setClass(view, trackableClass)

        // Now we can create the associated object
        objc_setAssociatedObject(view, &amp;RuntimeConstants.CounterKey, 0, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)

        // Adding our layoutSubviews implementation
        let layoutSubviews: @convention(block) (Any?) -&gt; () = { nullableSelf in
            guard let _self = nullableSelf else { return }

            let selector = #selector(originalClass.layoutSubviews)
            let originalImpl = class_getMethodImplementation(originalClass, selector)

            // @convention(c) tells Swift this is a bare function pointer (with no context object)
            // All Obj-C method functions have the receiver and message as their first two parameters
            // Therefore this denotes a method of type `() -&gt; Void`, which matches up with `layoutSubviews`
            typealias ObjCVoidVoidFn = @convention(c) (Any, Selector) -&gt; Void
            let originalLayoutSubviews = unsafeBitCast(originalImpl, to: ObjCVoidVoidFn.self)
            originalLayoutSubviews(view, selector)

            if let counter = objc_getAssociatedObject(_self, &amp;RuntimeConstants.CounterKey) as? Int {
                if counter == threshold {
                    onLoop()
                }

                objc_setAssociatedObject(view, &amp;RuntimeConstants.CounterKey, counter+1, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
        let implementation = imp_implementationWithBlock(layoutSubviews)
        class_addMethod(trackableClass, #selector(originalClass.layoutSubviews), implementation, &#x201C;v@:&#x201C;)
    } else if let trackableClass = NSClassFromString(classFullName) {
        // We&#x2019;ve previously allocated a class with the same name in this runtime session
        // We can get it from our raw string and swap with our view the same way
        object_setClass(view, trackableClass)
    }
}
</code></pre>
<p>Let&#x2019;s test it by creating a simulated layout loop for a view and setting our counter for it:</p>
<pre><code>class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        LayoutLoopHunter.setUp(for: view) {
            print(&quot;Hello, world&quot;)
        }
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        view.setNeedsLayout() // loop creation
    }
}
</code></pre>
<p>Did we miss something? Let&#x2019;s recall again how the <code>UIViewLayoutFeedbackLoopDebuggingThreshold</code> breakpoint works:</p>
<blockquote><p>Defines how many times a view must layout its subviews in a single run loop before it is considered to be a feedback loop.</p></blockquote>
<p>We never took into account the &#x201C;single run loop&#x201D; condition. If our view stays in the screen for a significant amount of time and is regularly being laid out over and over again, sooner or later our counter will exceed the threshold. But this is not because of a memory issue.</p>
<p>How do we solve this? Simply by resetting the counter on every run loop iteration. For doing so, we can create a <a href="https://www.appcoda.com/grand-central-dispatch/">DispatchWorkItem</a> which resets our counter and pass it asynchronously on the main queue. This way, it will be called when the run loop enters the main thread next time:</p>
<pre><code class="swift">static var ResetWorkItemKey = &#x201C;_resetWorkItem&#x201D;

...

if let previousResetWorkItem = objc_getAssociatedObject(view, &amp;RuntimeConstants.ResetWorkItemKey) as? DispatchWorkItem {
    previousResetWorkItem.cancel()
}
let currentResetWorkItem = DispatchWorkItem { [weak view] in
    guard let strongView = view else { return }
    objc_setAssociatedObject(strongView, &amp;RuntimeConstants.CounterKey, 0, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
DispatchQueue.main.async(execute: currentResetWorkItem)
objc_setAssociatedObject(view, &amp;RuntimeConstants.ResetWorkItemKey, currentResetWorkItem, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
</code></pre>
<p>The final code:</p>
<pre><code>struct LayoutLoopHunter {

    struct RuntimeConstants {
        static let Prefix = &#x201C;runtime&#x201D;

        // Associated objects keys
        static var CounterKey = &#x201C;_counter&#x201D;
        static var ResetWorkItemKey = &#x201C;_resetWorkItem&#x201D;
    }

    static func setUp(for view: UIView, threshold: Int = 100, onLoop: @escaping () -&gt; ()) {
        // We create the name for our new class based on the prefix for our feature and the original class name
        let classFullName = &#x201C;\(RuntimeConstants.Prefix)_\(String(describing: view.self))&#x201D;
        let originalClass = type(of: view)

        if let trackableClass = objc_allocateClassPair(originalClass, classFullName, 0) {
            // This class hasn&#x2019;t been created during the current runtime session
            // We need to register our class and swap is with the original view&#x2019;s class
            objc_registerClassPair(trackableClass)
            object_setClass(view, trackableClass)

            // Now we can create the associated object
            objc_setAssociatedObject(view, &amp;RuntimeConstants.CounterKey, 0, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)

            // Adding our layoutSubviews implementation
            let layoutSubviews: @convention(block) (Any?) -&gt; () = { nullableSelf in
                guard let _self = nullableSelf else { return }

                let selector = #selector(originalClass.layoutSubviews)
                let originalImpl = class_getMethodImplementation(originalClass, selector)

                // @convention(c) tells Swift this is a bare function pointer (with no context object)
                // All Obj-C method functions have the receiver and message as their first two parameters
                // Therefore this denotes a method of type `() -&gt; Void`, which matches up with `layoutSubviews`
                typealias ObjCVoidVoidFn = @convention(c) (Any, Selector) -&gt; Void
                let originalLayoutSubviews = unsafeBitCast(originalImpl, to: ObjCVoidVoidFn.self)
                originalLayoutSubviews(view, selector)

                if let counter = objc_getAssociatedObject(_self, &amp;RuntimeConstants.CounterKey) as? Int {
                    if counter == threshold {
                        onLoop()
                    }

                    objc_setAssociatedObject(view, &amp;RuntimeConstants.CounterKey, counter+1, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                }

                // Dispatch work item for reseting the counter on every new run loop iteration
                if let previousResetWorkItem = objc_getAssociatedObject(view, &amp;RuntimeConstants.ResetWorkItemKey) as? DispatchWorkItem {
                    previousResetWorkItem.cancel()
                }
                let counterResetWorkItem = DispatchWorkItem { [weak view] in
                    guard let strongView = view else { return }
                    objc_setAssociatedObject(strongView, &amp;RuntimeConstants.CounterKey, 0, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                }
                DispatchQueue.main.async(execute: counterResetWorkItem)
                objc_setAssociatedObject(view, &amp;RuntimeConstants.ResetWorkItemKey, counterResetWorkItem, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
            let implementation = imp_implementationWithBlock(layoutSubviews)
            class_addMethod(trackableClass, #selector(originalClass.layoutSubviews), implementation, &#x201C;v@:&#x201C;)
        } else if let trackableClass = NSClassFromString(classFullName) {
            // We&#x2019;ve previously allocated a class with the same name in this runtime session
            // We can get it from our raw string and swap with our view the same way
            object_setClass(view, trackableClass)
        }
    }
}
</code></pre>
<h2>Conclusion</h2>
<p>That&#x2019;s it! Now you can set up analytics events for all your suspicious views, release the app and find out where exactly the issue occurs. You can narrow it down to a particular view and resolve the issue with the help of your users without them even knowing about this.</p>
<p>One last thing to mention is that with great power comes great responsibility. Runtime programming is very error-prone so it&#x2019;s very easy to introduce another critical issue for your app without knowing. That&#x2019;s why it&#x2019;s always recommended to wrap all the dangerous code in your app in some kind of killswitch which you can trigger from the backend and disable the feature when you see that it&#x2019;s causing issues. <a href="https://medium.com/@rwbutler/feature-flags-a-b-testing-mvt-on-ios-718339ac7aa1?ref=appcoda.com">Here</a> is a nice article about Feature Flags from Firebase.</p>
<p>The full code is available in this <a href="https://github.com/rsrbk/LayoutLoopHunter?ref=appcoda.com">GitHub repository</a> and also being distributed via CocoaPods for tracking Layout Loops in your projects.</p>
<p>P.S. I want to say special thanks to <a href="https://github.com/sanekgusev?ref=appcoda.com">Aleksandr Gusev</a> for his help with reviewing and giving more ideas for this article.</p>

<!--kg-card-end: html-->
]]></content:encoded></item><item><title><![CDATA[Using CocoaPods in Your Swift and Objective-C Projects]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>Understanding CocoaPods, a dependency manager for Swift and Objective-C projects, is a critical skill every iOS developer should have.  If you have no experience with CocoaPods, this short post is written for you. We&#x2019;re going to take a look at what CocoaPods is, why you should start using</p>]]></description><link>https://www.appcoda.com/cocoapods/</link><guid isPermaLink="false">66612a0f166d3c03cf0113f8</guid><category><![CDATA[Objective C]]></category><dc:creator><![CDATA[Gregg Mojica]]></dc:creator><pubDate>Fri, 24 Jun 2016 11:02:26 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-orange-on-grey.jpg" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-orange-on-grey.jpg" alt="Using CocoaPods in Your Swift and Objective-C Projects"><p>Understanding CocoaPods, a dependency manager for Swift and Objective-C projects, is a critical skill every iOS developer should have.  If you have no experience with CocoaPods, this short post is written for you. We&#x2019;re going to take a look at what CocoaPods is, why you should start using it, and how to setup a project with cocoa pods installed!</p>
<p>While most of our tutorials are very detailed, this tutorial is much shorter than a traditional article and only intended to get you off the ground with Cocoapods.</p>
<h2>What is CocoaPods?</h2>
<p>CocoaPods is a dependency manager for Swift and Objective-C projects. If you&#x2019;ve ever used Node.js, Ruby on Rails, Python, etc., you&#x2019;re probably familiar with the concept of a dependency manager. If not, that&#x2019;s okay! A dependency manger is a tool that manages a set of frameworks and packages for developers. So instead of having to manually import files via drop and drop, a dependency manager like CocoaPods takes care of all that for you.</p>
<p>Consider this sample scenario: <em>You&#x2019;re working on an app and need to make use of a third party framework like Firebase.</em></p>
<p>Firebase relies on several other frameworks to work. In order to use it, you have to import all the frameworks Firebase requires, plus Firebase itself. This is a tedious process if you have to do it manually.</p>
<p>Let&#x2019;s take this example even further. If Firebase ships an update to their SDK, you&#x2019;ll have to redownload the entire SDK and replace it manually.</p>
<p>This is why CocoaPods has its place. It simplifies the whole process by automatically finding and installing the frameworks, or dependencies require. You will understand the power of CocoaPods in a minute.</p>
<h2>Setting Up CocoaPods on Your Mac</h2>
<p>Setting up Cocoapods is simple and straightforward, and a very rewarding process. To install Cocoapods, navigate to the terminal and type the following commands:</p>
<pre>
sudo gem install cocoapods
</pre>
<p>This line of command installs the CocoaPods gem on your system. CocoaPods was built with Ruby, so it relies on the default Ruby available on OS X for installation. If you&#x2019;re familiar with Ruby, gems in Ruby are similar to pods in CocoaPods.</p>
<p>You may be prompted to enter your root password and then hit enter. Note that the password will not appear on screen as terminal does not display passwords.</p>
<p><img loading="lazy" decoding="async" src="http://www.appcoda.com/wp-content/uploads/2016/06/cocoapods-install-1024x579.png" alt="Using CocoaPods in Your Swift and Objective-C Projects" width="1024" height="579" class="aligncenter size-large wp-image-8248" srcset="https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-install-1024x579.png 1024w, https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-install-200x113.png 200w, https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-install-531x300.png 531w, https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-install-768x434.png 768w, https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-install-610x345.png 610w, https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-install-1680x949.png 1680w, https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-install-1240x701.png 1240w, https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-install-860x486.png 860w, https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-install-680x384.png 680w, https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-install-400x226.png 400w, https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-install-50x28.png 50w, https://www.appcoda.com/content/images/wordpress/2016/06/cocoapods-install.png 1780w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>It&#x2019;ll take several minutes to finish the installation. Just be patient, grab a cup of coffee, and wait the whole process to complete.</p>
<h2>Using CocoaPods for Xcode Projects</h2>
<p>Once you have CocoaPods installed on your Mac, let&#x2019;s see how to use it. We will create a sample project and demonstrate how you can install the Firebase framework in the project using CocoaPods.</p>
<p>First, create a new Xcode project and name it <code>CocoapodsTest</code>.  Close the project and back in terminal. Use the <code>cd</code> (change directory) command to navigate to your new Xcode project. Assuming you save the project under <code>Desktop</code>, here is the command:</p>
<pre>
cd ~/Desktop/CocoapodsTest
</pre>
<p>Next, we need to create what&#x2019;s called a Podfile. A Podfile is a file that lives in the root of your project and is responsible for keeping track of all the pods you want to install. When you ask CocoaPods to install any pods or updates to your existing pods, CocoaPods will look to the Podfile for instructions.</p>
<p>To create a Podfile, simply type the following command:</p>
<pre>
pod init
</pre>
<p>CocoaPod then generates the Podfile like this:</p>
<pre>
# Uncomment this line to define a global platform for your project
# platform :ios, &apos;9.0&apos;

target &apos;CocoapodsTest&apos; do
  # Comment this line if you&apos;re not using Swift and don&apos;t want to use dynamic frameworks
  use_frameworks!

  # Pods for CocoapodsTest

end
</pre>
<p>That&#x2019;s the basic structure of a Podfile. All you need to do is edit the file and specify your required pods. We are going to use a text editor called Vim to edit the file. Vim is a program built into every Mac that allows developers to edit content within terminal. That said, you&#x2019;re free to use other text editors like <a href="https://atom.io/?ref=appcoda.com">Atom</a>.</p>
<p>Type the following command to open the file with vim:</p>
<pre>
vim Podfile
</pre>
<p>Suppose you&#x2019;re going to use Firebase in your Xcode project.  To do so, edit the file content like this to configure the Firebase pod.</p>
<pre mark="9">
# Uncomment this line to define a global platform for your project
# platform :ios, &apos;9.0&apos;

target &apos;CocoapodsTest&apos; do
  # Comment this line if you&apos;re not using Swift and don&apos;t want to use dynamic frameworks
  use_frameworks!

  # Pods for CocoapodsTest
  pod &apos;Firebase&apos;
end
</pre>
<p>That&#x2019;s it. To exit vim, hit the escape key and then type:</p>
<pre>
:wq
</pre>
<p>This means write and quit, which will close vim with your changes saved.</p>
<p>Before we move to the last step, let us go through the above configuration:</p>
<ul>
<li>The Podfile describes the dependencies of the targets of your Xcode project. Therefore, we have to specify the target, which is CocoapodsTest for this demo.</li>
<li>The <code>use_frameworks</code> option tells CocoaPods to use frameworks instead of static libraries. This is required for Swift projects.</li>
<li>The line that we have just inserted (<code>pod &apos;Firebase&apos;</code>) lets CocoaPods know that we need to use the <code>Firebase</code> pod. You may wonder how do you know the pod name. Normally you can look it up in the documentation of the pod or simply search it on <a href="https://cocoapods.org/?ref=appcoda.com">cocoapods.org</a>.</li>
</ul>
<p><img loading="lazy" decoding="async" src="http://www.appcoda.com/wp-content/uploads/2016/06/pod-cocoapods-org-1024x570.jpg" alt="Using CocoaPods in Your Swift and Objective-C Projects" width="1024" height="570" class="aligncenter size-large wp-image-8257" srcset="https://www.appcoda.com/content/images/wordpress/2016/06/pod-cocoapods-org-1024x570.jpg 1024w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-cocoapods-org-200x111.jpg 200w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-cocoapods-org-539x300.jpg 539w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-cocoapods-org-768x427.jpg 768w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-cocoapods-org-610x339.jpg 610w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-cocoapods-org-1240x690.jpg 1240w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-cocoapods-org-860x478.jpg 860w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-cocoapods-org-680x378.jpg 680w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-cocoapods-org-400x223.jpg 400w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-cocoapods-org-50x28.jpg 50w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-cocoapods-org.jpg 1280w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>Now that you should have a better understanding of the pod file, type the following command in the terminal to complete the last step:</p>
<pre>
pod install
</pre>
<p>Cocoapods will now install the Firebase pod! After downloading the Firebase pods, it creates a workspace file named <code>CocoapodsTest.xcworkspace</code>. This workspace file bundles your original Xcode project, the Firebase library, and its dependencies.</p>
<p><img loading="lazy" decoding="async" src="http://www.appcoda.com/wp-content/uploads/2016/06/pod-install-1024x467.jpg" alt="Using CocoaPods in Your Swift and Objective-C Projects" width="1024" height="467" class="aligncenter size-large wp-image-8267" srcset="https://www.appcoda.com/content/images/wordpress/2016/06/pod-install-1024x467.jpg 1024w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-install-200x91.jpg 200w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-install-600x274.jpg 600w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-install-768x350.jpg 768w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-install-610x278.jpg 610w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-install-1240x566.jpg 1240w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-install-860x392.jpg 860w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-install-680x310.jpg 680w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-install-400x183.jpg 400w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-install-50x23.jpg 50w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-install.jpg 1280w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>So from now on, you have to use <code>CocoapodsTest.xcworkspace</code> instead of <code>CocoapodsTest.xcodeproj</code>.</p>
<h2>Opening the Xcode Workspace</h2>
<p>If you open <code>CocoapodsTest.xcworkspace</code> with Xcode, you should find both the <code>CocoapodsTest</code> project and the <code>Pod</code> project, which contains the <code>Firebase</code> library.</p>
<p><img loading="lazy" decoding="async" src="http://www.appcoda.com/wp-content/uploads/2016/06/pod-xcode-workspace-1024x596.png" alt="Using CocoaPods in Your Swift and Objective-C Projects" width="1024" height="596" class="aligncenter size-large wp-image-8253" srcset="https://www.appcoda.com/content/images/wordpress/2016/06/pod-xcode-workspace-1024x596.png 1024w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-xcode-workspace-200x116.png 200w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-xcode-workspace-515x300.png 515w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-xcode-workspace-768x447.png 768w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-xcode-workspace-610x355.png 610w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-xcode-workspace-1680x978.png 1680w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-xcode-workspace-1240x722.png 1240w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-xcode-workspace-860x501.png 860w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-xcode-workspace-680x396.png 680w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-xcode-workspace-400x233.png 400w, https://www.appcoda.com/content/images/wordpress/2016/06/pod-xcode-workspace-50x29.png 50w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>Now all there&#x2019;s left to do is use the Firebase pod. Let&#x2019;s navigate back to Xcode and inside the IDE, go to <code>ViewController.swift</code>. At the top, type:</p>
<pre>
import Firebase
</pre>
<p>And look at that! You are up and running with CocoaPods!</p>
<h2>Wrapping Up</h2>
<p>CocoaPods is an incredibly simple tool that every iOS developer should have in his/her backpocket. I hope this tutorial is clear cut and easy to follow. If you have any thoughts or questions, please leave them in the comment.</p>
<div class="alert gray"><strong>Editor&#x2019;s note</strong>: Apple is going to release the <a href="https://swift.org/package-manager/?ref=appcoda.com">Swift Package Manager</a>, which is very similar to CocoaPods, and is integrated into the Swift build system to automate the process of dependencies management. The Swift Package Manager will be available this fall. We will talk more about that when it is officially released. <a href="https://www.facebook.com/appcodamobile">Stay tuned</a>.</div>

<!--kg-card-end: html-->
]]></content:encoded></item><item><title><![CDATA[How to Use Xcode Targets to Manage Development and Production Builds]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p><em>Editor&#x2019;s note: This is a guest post contributed by Eugene Trapeznikov. Imagine you&#x2019;ve completed the development and testing of your app, you&#x2019;re now ready to submit it for production release. The problem is that some of the web service URLs are pointing to the</em></p>]]></description><link>https://www.appcoda.com/using-xcode-targets/</link><guid isPermaLink="false">66612a0f166d3c03cf0113da</guid><category><![CDATA[Objective C]]></category><category><![CDATA[Swift]]></category><category><![CDATA[Xcode]]></category><dc:creator><![CDATA[Eugene Trapeznikov]]></dc:creator><pubDate>Mon, 18 Jan 2016 12:14:50 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2016/01/xcode-targets.jpg" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://www.appcoda.com/content/images/wordpress/2016/01/xcode-targets.jpg" alt="How to Use Xcode Targets to Manage Development and Production Builds"><p><em>Editor&#x2019;s note: This is a guest post contributed by Eugene Trapeznikov. Imagine you&#x2019;ve completed the development and testing of your app, you&#x2019;re now ready to submit it for production release. The problem is that some of the web service URLs are pointing to the testing servers, and the API keys are configured for the test environment. Before submitting the app for Apple&#x2019;s review, you&#x2019;ll need to modify all these API keys and URLs to fit for production. This sounds good, right? But instead of changing the values back and forth between the development and production environment, is there a better approach to handle both the development and production builds? This is exactly what Eugene is going to discuss with you.</em></p>
<p>Enter Eugene&#x2019;s tutorial.</p>
<p>For starters, some of you may be wondering why you should use two separate databases and environments while developing your app.  The reason is because as you continue to build new features or develop your app, you want to separate the development version from the existing public production app.  Standard software development practice is to use different environments for the different versions of the software, and in our case, iPhone apps.  The development version of an app typically uses a different database (or other systems such as analytics) from  the production environment. This is one reason why we should use separate servers and databases for different environments.  Developers commonly use dummy images or data during testing. In testing or development environments, it&#x2019;s not uncommon for one to use test data such as &#x201C;test comment&#x201D;, &#x201C;argharghargh&#x201D; and &#x201C;one more test comment&#x201D;. Obviously, you don&#x2019;t want your real users to see these kind of messages. In the case of if your app using an analytics system, you may even send thousands of events during the testing stage. Again, you don&#x2019;t want to mix the test data with the production data in the same database. This is why its always recommended to separate the development and production environments.</p>
<p>While using two separate environments, your app needs to have a way to find out which environment it should connect to. One popular method is to define a global variable in your main app delegate, which will initialize your app to development or production mode.</p>
<pre lang="swift">
enum environmentType {
    case development, production
}

let environment:environmentType = .production

switch environment {
case .development:
    // set web service URL to development
    // set API keys to development
    print(&quot;It&apos;s for development&quot;)
case .production:
    // set web service URL to production
    // set API keys to production
    print(&quot;It&apos;s for production&quot;)
}
</pre>
<p>This approach requires you to change the global variable every time you want to switch from one environment to another. While this method maybe quick and convenient, it comes with some major limitations. First, because we are using a single bundle ID for both the development and production environments, you cannot install both app versions on a single device. This becomes inconvenient when you want to test the development version of the app, but still use the production version of the app on the same device. Also, this approach allows for an opportunity to accidentally ship the development app to the store.  If you forget to change that single global variable, you will be shipping the wrong app to your users. I remember once I forgot to change the global variable before submitting my app to the App Store, and users got the development version of the app. That was awful.</p>
<p>In this article I will show you a better approach to differentiate between the development and production builds. Specifically, we will create a development target in XCode. This method is suitable for both new and existing large projects, so you can use one of your existing apps to follow along in this tutorial.  </p>
<p>By applying this approach, the production and development versions of the app will have the same base code, but can have different icons, bundle IDs and point to separate databases. The distribution and submission processes will be very straightforward. Most importantly, your testers and managers will be able to install both versions of the app on the same device, so they fully understand which version they&#x2019;re trying out. </p>
<h2>How to Create a New Target</h2>
<p>So how can you create a development target in Xcode? I will walk you through the procedure step-by-step with my template project &#x201C;todo&#x201D;. You can use your own project and follow the procedures:</p>
<p>1. Go to project&#x2019;s settings in the Project Navigator panel. Under the <em>Targets</em> sections, right click the existing target and select <code>Duplicate</code> to copy your existing target.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-7339" src="http://www.appcoda.com/wp-content/uploads/2016/01/Duplicate-target.png" alt="How to Use Xcode Targets to Manage Development and Production Builds" width="1664" height="800" srcset="https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-target.png 1664w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-target-200x96.png 200w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-target-600x288.png 600w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-target-768x369.png 768w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-target-1024x492.png 1024w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-target-610x293.png 610w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-target-1240x596.png 1240w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-target-860x413.png 860w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-target-680x327.png 680w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-target-400x192.png 400w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-target-50x24.png 50w" sizes="(max-width: 1664px) 100vw, 1664px"></p>
<p>2. Xcode will ask you if your new target is for iPad development. For this tutorial, we just select &#x201C;Duplicate Only&#x201D;.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-7338" src="http://www.appcoda.com/wp-content/uploads/2016/01/Duplicate-only.png" alt="How to Use Xcode Targets to Manage Development and Production Builds" width="1472" height="564" srcset="https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-only.png 1472w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-only-200x77.png 200w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-only-600x230.png 600w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-only-768x294.png 768w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-only-1024x392.png 1024w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-only-610x234.png 610w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-only-1240x475.png 1240w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-only-860x330.png 860w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-only-680x261.png 680w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-only-400x153.png 400w, https://www.appcoda.com/content/images/wordpress/2016/01/Duplicate-only-50x19.png 50w" sizes="(max-width: 1472px) 100vw, 1472px"></p>
<div class="alert gray"><strong>Note:</strong> If your project supports universal devices, Xcode will not prompt the above message.</div>
<p>3. Now that we have a new target and a new build scheme with the name <code>todo copy</code>. Let&#x2019;s rename it so it is easier to understand.</p>
<ul>
<li>Select the new target in the <em>TARGETS</em> list. Press <code>Enter</code> to edit the text and put a more appropriate name. I prefer &#x201C;todo Dev&#x201D;. You&#x2019;re free to choose whatever name you like.</li>
<li>Next, go to &#x201C;Manage Schemes&#x2026;&#x201D;, select the new scheme you created in step 1 and press &#x201C;Enter&#x201D;. Make the scheme name the same as the new target name (which is the one you choose for the new target.)</li>
</ul>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-7342" src="http://www.appcoda.com/wp-content/uploads/2016/01/Targetandscheme.png" alt="How to Use Xcode Targets to Manage Development and Production Builds" width="844" height="382" srcset="https://www.appcoda.com/content/images/wordpress/2016/01/Targetandscheme.png 844w, https://www.appcoda.com/content/images/wordpress/2016/01/Targetandscheme-200x91.png 200w, https://www.appcoda.com/content/images/wordpress/2016/01/Targetandscheme-600x272.png 600w, https://www.appcoda.com/content/images/wordpress/2016/01/Targetandscheme-768x348.png 768w, https://www.appcoda.com/content/images/wordpress/2016/01/Targetandscheme-610x276.png 610w, https://www.appcoda.com/content/images/wordpress/2016/01/Targetandscheme-680x308.png 680w, https://www.appcoda.com/content/images/wordpress/2016/01/Targetandscheme-400x181.png 400w, https://www.appcoda.com/content/images/wordpress/2016/01/Targetandscheme-50x23.png 50w" sizes="(max-width: 844px) 100vw, 844px"></p>
<p>4. Steps 4 is optional, but highly recommended.  If you want to make it easy and dummy-proof to distinguish between the development and production builds, you should use separate icons and launch screens for each version.  This will make it obvious for your testers to know which app they are using, and hopefully prevent you from shipping a development version. &#x1F642; </p>
<p>Go to <code>Assets.xcassets</code> and add a new icon. Right click icon &gt; App Icons &amp; Launch Images &gt; New iOS App Icon. Rename the new icon to &#x201C;AppIcon-Dev&#x201D; and add your own images. </p>
<p><img loading="lazy" decoding="async" src="http://www.appcoda.com/wp-content/uploads/2016/01/image-asset-dev.jpg" alt="How to Use Xcode Targets to Manage Development and Production Builds" width="1280" height="821" class="aligncenter size-full wp-image-7363" srcset="https://www.appcoda.com/content/images/wordpress/2016/01/image-asset-dev.jpg 1280w, https://www.appcoda.com/content/images/wordpress/2016/01/image-asset-dev-200x128.jpg 200w, https://www.appcoda.com/content/images/wordpress/2016/01/image-asset-dev-468x300.jpg 468w, https://www.appcoda.com/content/images/wordpress/2016/01/image-asset-dev-768x493.jpg 768w, https://www.appcoda.com/content/images/wordpress/2016/01/image-asset-dev-1024x657.jpg 1024w, https://www.appcoda.com/content/images/wordpress/2016/01/image-asset-dev-610x391.jpg 610w, https://www.appcoda.com/content/images/wordpress/2016/01/image-asset-dev-1240x795.jpg 1240w, https://www.appcoda.com/content/images/wordpress/2016/01/image-asset-dev-860x552.jpg 860w, https://www.appcoda.com/content/images/wordpress/2016/01/image-asset-dev-680x436.jpg 680w, https://www.appcoda.com/content/images/wordpress/2016/01/image-asset-dev-400x257.jpg 400w, https://www.appcoda.com/content/images/wordpress/2016/01/image-asset-dev-50x32.jpg 50w" sizes="(max-width: 1280px) 100vw, 1280px"></p>
<p>5. Now go back to project settings, select your development target and change the bundle identifier. Say, you can simply append &#x201C;Dev&#x201D; to the original ID. If you performed step 4, make sure you change the app icon setting to the one created in the previous step.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-7340" src="http://www.appcoda.com/wp-content/uploads/2016/01/NewAppIDIcon.png" alt="How to Use Xcode Targets to Manage Development and Production Builds" width="1250" height="786" srcset="https://www.appcoda.com/content/images/wordpress/2016/01/NewAppIDIcon.png 1250w, https://www.appcoda.com/content/images/wordpress/2016/01/NewAppIDIcon-200x126.png 200w, https://www.appcoda.com/content/images/wordpress/2016/01/NewAppIDIcon-477x300.png 477w, https://www.appcoda.com/content/images/wordpress/2016/01/NewAppIDIcon-768x483.png 768w, https://www.appcoda.com/content/images/wordpress/2016/01/NewAppIDIcon-1024x644.png 1024w, https://www.appcoda.com/content/images/wordpress/2016/01/NewAppIDIcon-610x384.png 610w, https://www.appcoda.com/content/images/wordpress/2016/01/NewAppIDIcon-1240x780.png 1240w, https://www.appcoda.com/content/images/wordpress/2016/01/NewAppIDIcon-860x541.png 860w, https://www.appcoda.com/content/images/wordpress/2016/01/NewAppIDIcon-680x428.png 680w, https://www.appcoda.com/content/images/wordpress/2016/01/NewAppIDIcon-400x252.png 400w, https://www.appcoda.com/content/images/wordpress/2016/01/NewAppIDIcon-50x31.png 50w" sizes="(max-width: 1250px) 100vw, 1250px"></p>
<p>6. Xcode automatically added a plist file for your target (e.g. todo copy-Info.plist). You can find it at the root folder of your project. Rename it from &#x201C;copy&#x201D; to &#x201C;Dev&#x201D;, and place it right below your original plist file. Here, it will be easier for you to manage the file.</p>
<p>7. Now open &#x201C;Build Settings&#x201D; of your development target, scroll to &#x201C;Packaging&#x201D;, and change the value to the development plist file (e.g. todo Dev.plist).</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-7341" src="http://www.appcoda.com/wp-content/uploads/2016/01/newplist.png" alt="How to Use Xcode Targets to Manage Development and Production Builds" width="1352" height="666" srcset="https://www.appcoda.com/content/images/wordpress/2016/01/newplist.png 1352w, https://www.appcoda.com/content/images/wordpress/2016/01/newplist-200x99.png 200w, https://www.appcoda.com/content/images/wordpress/2016/01/newplist-600x296.png 600w, https://www.appcoda.com/content/images/wordpress/2016/01/newplist-768x378.png 768w, https://www.appcoda.com/content/images/wordpress/2016/01/newplist-1024x504.png 1024w, https://www.appcoda.com/content/images/wordpress/2016/01/newplist-610x300.png 610w, https://www.appcoda.com/content/images/wordpress/2016/01/newplist-1240x611.png 1240w, https://www.appcoda.com/content/images/wordpress/2016/01/newplist-860x424.png 860w, https://www.appcoda.com/content/images/wordpress/2016/01/newplist-680x335.png 680w, https://www.appcoda.com/content/images/wordpress/2016/01/newplist-400x197.png 400w, https://www.appcoda.com/content/images/wordpress/2016/01/newplist-50x25.png 50w" sizes="(max-width: 1352px) 100vw, 1352px"></p>
<p>8. Lastly, we&#x2019;ll configure a preprocessing macro/compiler flag for both production and development targets. So later we can use the flag in our code to detect which version the app is currently running. </p>
<p>For Objective-C projects, go to <code>Build Settings</code> and scroll to <code>Apple LLVM 7.0 - Preprocessing</code>. Expand <code>Preprocessor Macros</code> and add a variable to both <em>Debug</em> and <em>Release</em> fields. For the development target (i.e. todo Dev), set the value to <code>DEVELOPMENT=1</code>. On the other hand, set the value to <code>DEVELOPMENT=0</code> to indicate a production version.</p>
<p><img loading="lazy" decoding="async" src="http://www.appcoda.com/wp-content/uploads/2016/01/dev-macro-1-1.png" alt="How to Use Xcode Targets to Manage Development and Production Builds" width="1550" height="600" class="aligncenter size-full wp-image-7365" srcset="https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-1-1.png 1550w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-1-1-200x77.png 200w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-1-1-600x232.png 600w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-1-1-768x297.png 768w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-1-1-1024x396.png 1024w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-1-1-610x236.png 610w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-1-1-1240x480.png 1240w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-1-1-860x333.png 860w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-1-1-680x263.png 680w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-1-1-400x155.png 400w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-1-1-50x19.png 50w" sizes="(max-width: 1550px) 100vw, 1550px"></p>
<p><img loading="lazy" decoding="async" src="http://www.appcoda.com/wp-content/uploads/2016/01/dev-macro-2-1.png" alt="How to Use Xcode Targets to Manage Development and Production Builds" width="1524" height="600" class="aligncenter size-full wp-image-7366" srcset="https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-2-1.png 1524w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-2-1-200x79.png 200w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-2-1-600x236.png 600w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-2-1-768x302.png 768w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-2-1-1024x403.png 1024w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-2-1-610x240.png 610w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-2-1-1240x488.png 1240w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-2-1-860x339.png 860w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-2-1-680x268.png 680w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-2-1-400x157.png 400w, https://www.appcoda.com/content/images/wordpress/2016/01/dev-macro-2-1-50x20.png 50w" sizes="(max-width: 1524px) 100vw, 1524px"></p>
<p>For Swift project, the compiler no longer supports preprocessor directives. Instead, it uses compile-time attributes and build configurations. To add a flag to indicate a development build, select the development target. Go to <code>Build Settings</code> and scroll down to the <code>Swift Compiler - Custom Flags</code> section. Set the value to <code>-DDEVELOPMENT</code> to indicate the target as a development build.</p>
<p><img loading="lazy" decoding="async" src="http://www.appcoda.com/wp-content/uploads/2016/01/swift-compiler-flag.png" alt="How to Use Xcode Targets to Manage Development and Production Builds" width="1694" height="616" class="aligncenter size-full wp-image-7360" srcset="https://www.appcoda.com/content/images/wordpress/2016/01/swift-compiler-flag.png 1694w, https://www.appcoda.com/content/images/wordpress/2016/01/swift-compiler-flag-200x73.png 200w, https://www.appcoda.com/content/images/wordpress/2016/01/swift-compiler-flag-600x218.png 600w, https://www.appcoda.com/content/images/wordpress/2016/01/swift-compiler-flag-768x279.png 768w, https://www.appcoda.com/content/images/wordpress/2016/01/swift-compiler-flag-1024x372.png 1024w, https://www.appcoda.com/content/images/wordpress/2016/01/swift-compiler-flag-610x222.png 610w, https://www.appcoda.com/content/images/wordpress/2016/01/swift-compiler-flag-1680x611.png 1680w, https://www.appcoda.com/content/images/wordpress/2016/01/swift-compiler-flag-1240x451.png 1240w, https://www.appcoda.com/content/images/wordpress/2016/01/swift-compiler-flag-860x313.png 860w, https://www.appcoda.com/content/images/wordpress/2016/01/swift-compiler-flag-680x247.png 680w, https://www.appcoda.com/content/images/wordpress/2016/01/swift-compiler-flag-400x145.png 400w, https://www.appcoda.com/content/images/wordpress/2016/01/swift-compiler-flag-50x18.png 50w" sizes="(max-width: 1694px) 100vw, 1694px"></p>
<p>Now that you have created and configured the development target, what&#x2019;s next?</p>
<h2>Using the Target and Macro</h2>
<p>With the macro <code>DEV_VERSION</code> configured, we can utilize it in the code and perform dynamic compilation for your project. Here is a simple example:</p>
<p><strong>Objective-C:</strong></p>
<pre lang="swift">
#if DEVELOPMENT
#define SERVER_URL @&quot;http://dev.server.com/api/&quot;
#define API_TOKEN @&quot;DI2023409jf90ew&quot;
#else
#define SERVER_URL @&quot;http://prod.server.com/api/&quot;
#define API_TOKEN @&quot;71a629j0f090232&quot;
#endif
</pre>
<p>In Objective-C, you can use <code>#if</code> to check the condition of <code>DEVELOPMENT</code>, and set up the URLs/API keys accordingly.</p>
<p><strong>Swift:</strong></p>
<pre lang="swift">
#if DEVELOPMENT
let SERVER_URL = &quot;http://dev.server.com/api/&quot;
let API_TOKEN = &quot;DI2023409jf90ew&quot;
#else
let SERVER_URL = &quot;http://prod.server.com/api/&quot;
let API_TOKEN = &quot;71a629j0f090232&quot;
#endif
</pre>
<p>In Swift, you can still use <code>#if</code> to evaluate the build configurations for dynamic compilations. However, instead of using <code>#define</code> to define a primitive constant, we simply use <code>let</code> to define a global constant in Swift.</p>
<div class="alert gray"><strong>Note:</strong> Usually, you will put the above code in the a pp delegate. But it really depends on where you initialize the app settings.</div>
<p>Now when you select the &#x201C;todo Dev&#x201D; scheme and run the project, you&#x2019;ll create the development build automatically with the server configuration set to the development environment. You&#x2019;re now ready to upload the development build to TestFlight or HockeyApp for your testers and managers to test out.</p>
<p>Later if you need to create a production build, you can simply select the &#x201C;todo&#x201D; scheme. No code change is required. </p>
<h2>Some Notes on Managing Multiple Targets</h2>
<p>1. When you add new files to the project, don&#x2019;t forget to select both targets to keep your code in sync in both builds.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-7335" src="http://www.appcoda.com/wp-content/uploads/2016/01/add-new-file.png" alt="How to Use Xcode Targets to Manage Development and Production Builds" width="1472" height="742" srcset="https://www.appcoda.com/content/images/wordpress/2016/01/add-new-file.png 1472w, https://www.appcoda.com/content/images/wordpress/2016/01/add-new-file-200x101.png 200w, https://www.appcoda.com/content/images/wordpress/2016/01/add-new-file-595x300.png 595w, https://www.appcoda.com/content/images/wordpress/2016/01/add-new-file-768x387.png 768w, https://www.appcoda.com/content/images/wordpress/2016/01/add-new-file-1024x516.png 1024w, https://www.appcoda.com/content/images/wordpress/2016/01/add-new-file-610x307.png 610w, https://www.appcoda.com/content/images/wordpress/2016/01/add-new-file-1240x625.png 1240w, https://www.appcoda.com/content/images/wordpress/2016/01/add-new-file-860x434.png 860w, https://www.appcoda.com/content/images/wordpress/2016/01/add-new-file-680x343.png 680w, https://www.appcoda.com/content/images/wordpress/2016/01/add-new-file-400x202.png 400w, https://www.appcoda.com/content/images/wordpress/2016/01/add-new-file-50x25.png 50w" sizes="(max-width: 1472px) 100vw, 1472px"></p>
<p>2. In case you&#x2019;re using Cocoapods, don&#x2019;t forget to add the new target to your podfile. You can use <code>link_with</code> to specify multiple targets. You can further consult the <a href="https://guides.cocoapods.org/?ref=appcoda.com">Cocoapods documentation</a> for details. Your podfile should look something like this:</p>
<pre>source &apos;https://github.com/CocoaPods/Specs.git&apos;
platform :ios, &apos;7.0&apos;
workspace &apos;todo&apos;
link_with &apos;todo&apos;, &apos;todo Dev&apos;
pod &apos;Mixpanel&apos;
pod &apos;AFNetworking&apos;
</pre>
<p>3. If you use continuous integration system such as <a href="https://travis-ci.org/?ref=appcoda.com">Travis CI</a> or <a href="https://jenkins-ci.org/?ref=appcoda.com">Jenkins</a>, don&#x2019;t forget to configure to build and deliver both targets.</p>
<p>What do you think about this tutorial? How do you manage your development and production builds? Leave me comment and share your thought.</p>

<!--kg-card-end: html-->
]]></content:encoded></item><item><title><![CDATA[Building a Simple Weather App using JSON and WatchKit]]></title><description><![CDATA[<!--kg-card-begin: html--><p><em>Editor&#x2019;s note: This is a guest post by Gregory Tareyev, a co-founder and iOS developer of Chill (<a href="http://iamchill.co/?ref=appcoda.com">iamchill.co</a>), the first wearable communication tool that lets you interact with your friends with a tap. In this tutorial, Gregory will share his experience on Apple Watch development and show</em></p>]]></description><link>https://www.appcoda.com/weather-watchkit-app/</link><guid isPermaLink="false">66612a0f166d3c03cf0113be</guid><category><![CDATA[Objective C]]></category><dc:creator><![CDATA[Simon Ng]]></dc:creator><pubDate>Wed, 12 Aug 2015 22:12:32 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-watchkit.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: html--><img src="https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-watchkit.jpg" alt="Building a Simple Weather App using JSON and WatchKit"><p><em>Editor&#x2019;s note: This is a guest post by Gregory Tareyev, a co-founder and iOS developer of Chill (<a href="http://iamchill.co/?ref=appcoda.com">iamchill.co</a>), the first wearable communication tool that lets you interact with your friends with a tap. In this tutorial, Gregory will share his experience on Apple Watch development and show you how to build a simple weather app using a third-party API and WatchKit. We have written a couple of tutorials about WatchKit. All of them are in Swift. Some readers mentioned if we can provide a tutorial in Objective-C. So here it is. </em></p>
<p>Enter Gregory&#x2019;s tutorial.</p>
<p>Hello everybody! My name is Gregory Tareyev (tareyev.ru for any contacts). I am a co-founder and iOS developer of Chill (iamchill.co), the first wearable communication tool that finally makes sense. Recently we had a great experience on <a href="http://www.producthunt.com/tech/chill?ref=appcoda.com">launching Chill on Product Hunt</a> which gave us a lot of visibility in the community and attracted major tech blogs to cover the release. We are also discussing our involvement with a few accelerators and considering the best one. We worked really hard to build the app, but I assure you that everybody can do something like that. </p>
<p>Here, I want to share some experience on the app development for Apple Watch. It&#x2019;ll be easy and fun.</p>
<p>To warm up your interest, I want to explain why it is so important to learn how to develop on wearable devices:</p>
<ol>
<li>The market is still small = you can get a bigger market share as a first-time mover</li>
<li>The market is going to grow tremendously = the product will grow along with the market</li>
</ol>
<p><img loading="lazy" decoding="async" width="600" height="450" src="http://www.appcoda.com/wp-content/uploads/2015/08/global-wearable-device-shipment.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6205" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/global-wearable-device-shipment.png 600w, https://www.appcoda.com/content/images/wordpress/2015/08/global-wearable-device-shipment-400x300.png 400w" sizes="(max-width: 600px) 100vw, 600px"></p>
<div class="note">Credit: The chart is provided by <a href="http://www.businessinsider.com/the-wearable-computing-market-report-2014-10?ref=appcoda.com">Business Insider</a>.</div>
<p>In this tutorial, we will build a simple weather app for Apple Watch. We will go through a couple of things:</p>
<ul>
<li>How to parse JSON in WatchKit app</li>
<li>How to use OpenWeatherMap API (once you understand it, you should be able to use any JSON-based APIs)</li>
</ul>
<p>So, let&#x2019;s get started! </p>
<h2>The Demo App</h2>
<p>The demo app is a very simple weather app. We&#x2019;re going to use OpenWeatherMap&#x2019;s API to get the weather information for a particular city (e.g. London). Here is the sample screen of the final app:</p>
<p><img loading="lazy" decoding="async" width="312" height="390" src="http://www.appcoda.com/wp-content/uploads/2015/08/weather-app.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6221" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/weather-app.png 312w, https://www.appcoda.com/content/images/wordpress/2015/08/weather-app-240x300.png 240w" sizes="(max-width: 312px) 100vw, 312px"></p>
<h2>Creating the Xcode Project</h2>
<p>First, create a Single View Application and configure the project option like below. Yes, we&#x2019;re going to write in Objective-C. I think it&#x2019;s still important, so let&#x2019;s not forget this wonderful language.</p>
<p><img loading="lazy" decoding="async" width="1024" height="601" src="http://www.appcoda.com/wp-content/uploads/2015/08/simple-weather-1.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6208" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-1.png 1024w, https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-1-511x300.png 511w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>To create a Watch app, go up to the Xcode menu and select Editor &gt; Add Target. Choose Apple Watch &gt; WatchKit App. By using the WatchKit App template, it will generate everything you need to build a Watch app.</p>
<p><img loading="lazy" decoding="async" width="1024" height="599" src="http://www.appcoda.com/wp-content/uploads/2015/08/simple-weather-add-target.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6210" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-add-target.png 1024w, https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-add-target-513x300.png 513w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>Deselect &#x201C;Include Notification Scene&#x201D; and leave other details as they are and then press finish. </p>
<p><img loading="lazy" decoding="async" width="1024" height="601" src="http://www.appcoda.com/wp-content/uploads/2015/08/simple-weather-watch-app.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6209" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-watch-app.png 1024w, https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-watch-app-511x300.png 511w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>Now you will get a warning to ask if you want to activate the new scheme. Just accept it. You&#x2019;ll then see two new folders: WatchKit Extension and WatchKit App.</p>
<p><img loading="lazy" decoding="async" width="1280" height="341" src="http://www.appcoda.com/wp-content/uploads/2015/08/simple-weather-watch-scheme.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6211" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-watch-scheme.png 1280w, https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-watch-scheme-600x160.png 600w, https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-watch-scheme-1024x273.png 1024w" sizes="(max-width: 1280px) 100vw, 1280px"></p>
<h2>Designing the UI</h2>
<p>Next, we will start to design the user interface of the Watch app. To do that, you have to navigate to &#x201C;SimpleWeather WatchKit App&#x201D; and select the Interface.Storyboard File.</p>
<p>First, drag a label from the Object library into the Interface Controller. Name it &#x201C;Weather in London&#x201D;. You may need to decrease the font size. Then drag an image, followed by a button into the Interface Controller. You will see that the image and button are layout automatically and stacked vertically. Change the title of the button to &#x201C;Update&#x201D; and color to green. Resize the image so that it looks like the screen below:</p>
<p><img loading="lazy" decoding="async" width="1280" height="707" src="http://www.appcoda.com/wp-content/uploads/2015/08/simple-weather-watch-ui.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6223" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-watch-ui.png 1280w, https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-watch-ui-543x300.png 543w, https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-watch-ui-1024x566.png 1024w" sizes="(max-width: 1280px) 100vw, 1280px"></p>
<p>The label is used to show the weather type, while the image shows an illustration of the weather type. The Update button is the only element that interacts with the user, and is used for updating the weather information.</p>
<p>Interface Builder lets you view the design on different version of Apple Watch. By default, the Interface Controller is set to Any Screen Size. You can click the &#x201C;Any Screen Size&#x201D; button at the bottom of the Interface Builder and switch to Apple Watch 38/42mm. If you switch to Apple Watch 42mm, you will find that the image is not perfectly fit. Just resize the image and make sure everything is layout correctly. As you change the size of the image, Xcode automatically adds layout specialisation, just for Apple Watch 42mm. </p>
<p><img loading="lazy" decoding="async" width="1280" height="786" src="http://www.appcoda.com/wp-content/uploads/2015/08/simple-weather-watch-ui-42.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6224" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-watch-ui-42.png 1280w, https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-watch-ui-42-489x300.png 489w, https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-watch-ui-42-1024x629.png 1024w" sizes="(max-width: 1280px) 100vw, 1280px"></p>
<h2>Understanding JSON and OpenWeatherMap&#x2019;s API</h2>
<p>As mentioned, we use OpenWeatherMap&#x2019;s API to get the weather data. To understand how it works, open this link: <a href="http://api.openweathermap.org/data/2.5/weather?q=London%2Cuk&amp;ref=appcoda.com">http://api.openweathermap.org/data/2.5/weather?q=London,uk</a>. Copy the resulting text and paste it into <a href="http://json.parser.online.fr/?ref=appcoda.com">http://json.parser.online.fr</a>. You&#x2019;ll see the JSON data, presented in a structured way. Here, what we are interested in is the weather type, i.e in the &#x201C;main&#x201D; key of the &#x201C;weather&#x201D; dictionary. This is the information we&#x2019;ll display it on screen.</p>
<p><img loading="lazy" decoding="async" width="1400" height="776" src="http://www.appcoda.com/wp-content/uploads/2015/08/openweather-api-json.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6214" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/openweather-api-json.png 1400w, https://www.appcoda.com/content/images/wordpress/2015/08/openweather-api-json-541x300.png 541w, https://www.appcoda.com/content/images/wordpress/2015/08/openweather-api-json-1024x568.png 1024w" sizes="(max-width: 1400px) 100vw, 1400px"></p>
<div class="note">For reference, you can refer to the API&#x2019;s documentation at http://openweathermap.org/api.</div>
<p>Now let&#x2019;s see how we can parse the JSON data and present the weather information in the app.</p>
<p>To begin, open the Assistant editor. Control-drag from the label to your code in InterfaceController.h file. Name the outlet &#x201C;weatherType&#x201D; like this:</p>
<p><img loading="lazy" decoding="async" width="1690" height="502" src="http://www.appcoda.com/wp-content/uploads/2015/08/add-label-outlet.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6215" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/add-label-outlet.png 1690w, https://www.appcoda.com/content/images/wordpress/2015/08/add-label-outlet-600x178.png 600w, https://www.appcoda.com/content/images/wordpress/2015/08/add-label-outlet-1024x304.png 1024w" sizes="(max-width: 1690px) 100vw, 1690px"></p>
<p>Repeat the same step for the image. Name the outlet &#x201C;weatherImage&#x201D; instead. When connecting the update button, instead of selecting Outlet, select Action and name it &#x201C;updateAction&#x201D;.</p>
<p><img loading="lazy" decoding="async" width="1400" height="333" src="http://www.appcoda.com/wp-content/uploads/2015/08/add-update-action.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6216" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/add-update-action.png 1400w, https://www.appcoda.com/content/images/wordpress/2015/08/add-update-action-600x143.png 600w, https://www.appcoda.com/content/images/wordpress/2015/08/add-update-action-1024x244.png 1024w" sizes="(max-width: 1400px) 100vw, 1400px"></p>
<p>Let&#x2019;s add logic in the <em>updateAction</em> method of the InterfaceController.m file:</p>
<pre lang="objc">
- (IBAction)updateAction
{
    NSURLRequest* requestForWeatherData = [NSURLRequest requestWithURL:[NSURL URLWithString:@&quot;http://api.openweathermap.org/data/2.5/weather?q=London,uk&quot;]];
    NSURLResponse* response = nil;
    NSError* error = nil; //do it always

    NSData* data = [NSURLConnection sendSynchronousRequest:requestForWeatherData returningResponse:&amp;response error:&amp;error]; //for saving all of received data in non-serialized view
    
    NSMutableDictionary *allData = [ NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&amp;error]; //data in serialized view
    NSString* currentWeather = nil;
    
    NSArray* weather = allData[@&quot;weather&quot;];
    
    for (NSDictionary* weatherDictionary in weather)
    {
        currentWeather = weatherDictionary[@&quot;main&quot;];
    }
}
</pre>
<p>In this method, we use NSURLConnection to make a synchronous request to the OpenWeatherMap API. You can use NSJSONSerialization to convert JSON to Foundation objects (e.g. NSDictionary). We parse the data and save the weather type in the &#x201C;currentWeather&#x201D; variable.</p>
<p>Next, we need to update the label and image. We can write something like this:</p>
<p><img loading="lazy" decoding="async" width="1156" height="558" src="http://www.appcoda.com/wp-content/uploads/2015/08/weather-image-if.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6217" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/weather-image-if.png 1156w, https://www.appcoda.com/content/images/wordpress/2015/08/weather-image-if-600x290.png 600w, https://www.appcoda.com/content/images/wordpress/2015/08/weather-image-if-1024x494.png 1024w" sizes="(max-width: 1156px) 100vw, 1156px"></p>
<p>The code is not very pretty, isn&#x2019;t it?</p>
<p>Instead of hardcoding the weather type, create a method like below, it&#x2019;ll make your code more flexible.</p>
<pre lang="objc">
-(void)setImageAndTextWithWeather:(NSString* ) weatherName
{
     // Use the weather type as the weather image name. For example, if the weather name is &quot;Rainy&quot;, the image name is set to &quot;rainy.jpg&quot;. 
     
     // Set the weather type to the given weather name
}
</pre>
<p>Awesome! Now let&#x2019;s turn the method into real code: </p>
<pre lang="objc">
-(void)setImageAndTextWithWeather:(NSString* ) weatherName
{
        NSString* weatherNameWithoutSpaces = [weatherName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //delete potential spaces in JSON array
        [_weatherImage setImageNamed:[weatherNameWithoutSpaces stringByAppendingString:@&quot;.jpg&quot;]];
    
    NSMutableAttributedString *customString = [[NSMutableAttributedString alloc] initWithString:weatherNameWithoutSpaces];
    [customString addAttribute:NSFontAttributeName
                         value:[UIFont systemFontOfSize:18] 
                  range:NSMakeRange(0, [weatherNameWithoutSpaces length])]; //Making text more readable by creating a custom string

    [_weatherType setAttributedText:customString];
}
</pre>
<p>Finally, add this line to the end of the updateAction method:  </p>
<pre lang="objc">
[self setImageAndTextWithWeather:currentWeather];
</pre>
<h2>Adding Images to the Asset Catalog</h2>
<p>One last thing before running the app. Download <a href="https://www.dropbox.com/s/p959x4w4uzhleuv/weather-images.zip?dl=0&amp;ref=appcoda.com">this image pack</a>, unzip it and add all the images to Images.xcassets under the SimpleWeather WatchKit App folder.</p>
<p><img loading="lazy" decoding="async" width="1280" height="435" src="http://www.appcoda.com/wp-content/uploads/2015/08/simple-weather-images.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6220" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-images.png 1280w, https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-images-600x204.png 600w, https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-images-1024x348.png 1024w" sizes="(max-width: 1280px) 100vw, 1280px"></p>
<p>You are free to add more images with appropriate weather names. The app will work properly without any code changes.</p>
<h2>Test the App</h2>
<p>That&#x2019;s it! Now You can build and run the app in the Apple Watch simulator. To run the app, select the &#x201C;WatchKitDemo WatchKit App&#x201D; scheme and choose your preferable device. Then click the run button to test the Watch app. Optionally, you can change the display size of the watch simulator by selecting Hardware &gt; External Displays &gt; Apple Watch &#x2013; 38mm.</p>
<p><img loading="lazy" decoding="async" width="1280" height="768" src="http://www.appcoda.com/wp-content/uploads/2015/08/simple-weather-simulator.png" alt="Building a Simple Weather App using JSON and WatchKit" class="aligncenter size-full wp-image-6218" srcset="https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-simulator.png 1280w, https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-simulator-500x300.png 500w, https://www.appcoda.com/content/images/wordpress/2015/08/simple-weather-simulator-1024x614.png 1024w" sizes="(max-width: 1280px) 100vw, 1280px"></p>
<p>Great! You&#x2019;ve built a weather app for Apple Watch. What do you think about tutorial? Leave me comment and share your thought. I love to hear your feedback.</p>
<p>For your reference, you can <a href="https://www.dropbox.com/s/wdg0zjpxgdjmpg8/SimpleWeather.zip?dl=0&amp;ref=appcoda.com">download the final project here</a>.</p>
<p><em>This is a guest post by Gregory Tareyev, a co-founder and iOS developer of Chill (<a href="http://iamchill.co/?ref=appcoda.com">iamchill.co</a>).</em></p>
<!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>During the development of an application there are various steps involved in the whole process. Some of them are the definition of its specifications, the creation of graphics, the implementation, and the testing phase following the implementation. Writing the code maybe consists of the most important part, as this brings</p>]]></description><link>https://www.appcoda.com/documenting-source-code-in-xcode/</link><guid isPermaLink="false">66612a0f166d3c03cf011399</guid><category><![CDATA[Objective C]]></category><category><![CDATA[Swift]]></category><category><![CDATA[Xcode]]></category><dc:creator><![CDATA[Gabriel Theodoropoulos]]></dc:creator><pubDate>Wed, 04 Feb 2015 00:49:36 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2015/02/xcode-macbook-featured.jpg" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://www.appcoda.com/content/images/wordpress/2015/02/xcode-macbook-featured.jpg" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen"><p>During the development of an application there are various steps involved in the whole process. Some of them are the definition of its specifications, the creation of graphics, the implementation, and the testing phase following the implementation. Writing the code maybe consists of the most important part, as this brings the application to life, but further than that, equally important is the proper <strong>documentation</strong> of the code. No matter how well-written the code is, if there&#x2019;s lack of a good documentation accompanying it, future troubles it&#x2019;s possible to arise. Unfortunately, many developers overlook or ignore the importance of the code documentation, and that&#x2019;s really bad, as good software is not just good code. It&#x2019;s more than that.</p>
<p>When talking about documentation, apparently I don&#x2019;t mean just to add a few lines of comments somewhere in the implementation files. It&#x2019;s definitely more than that. But first, why is it such a big deal to document the code? Well, there are two cases: Whether you&#x2019;re working on your own, or you are a part of a team. Let&#x2019;s see in short each one.</p>
<p><img loading="lazy" decoding="async" width="1024" height="672" src="http://www.appcoda.com/wp-content/uploads/2015/02/xcode-macbook-featured.jpg" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4808" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/xcode-macbook-featured.jpg 1024w, https://www.appcoda.com/content/images/wordpress/2015/02/xcode-macbook-featured-457x300.jpg 457w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>If you are the only developer of the under-development application, then it&#x2019;s reasonable to believe that writing code documentation costs in time, so skipping doing that will bring you right into your target much sooner. Additionally, it&#x2019;s easy to convince yourself that as you&#x2019;re the sole developer there&#x2019;s really no need to do that. But trust me, that&#x2019;s the worst decision you might make during the app creation period. Suppose that you successfully implement the application, you sell it either on the app store or in a client of yours, and then you put it in the shelf. And after six months or so, you must create a new version of it by adding new features. When you open the project again and look to the existing code, a long before you write the first new line, you realize one killing truth: That you don&#x2019;t remember almost anything! It&#x2019;s hard to remember what you did, how you did it, and why! You must follow the one, painful way to wake that project up in your mind, which is no other than taking the project from the beginning and trying to &#x201C;decode&#x201D; your implementation line by line. Just a few comments here and there are not helpful, and eventually you end up making a super-effort for a long time until you understand everything. Many of you that you are now reading these lines may have come to that point, and I ensure you that there were times that I&#x2019;ve been there too. This case is a real nightmare, and you often want to start building the project from scratch. And of course, the scenario described here would just be a&#x2026; scenario, if we all invested a little time to write proper code documentation.</p>
<p>On the other hand, if you&#x2019;re working on a project as a member of a team, then avoiding documenting your code would be catastrophic. When you share code with other developers, you must explain up to a point what you do (in the code) and how you do it, and of course other developers are required to do that too. There&#x2019;s no case developers in big projects to fully understand the code of other fellow developers, as among all, that leads to unneeded waste of time. So, writing documentation in this case it&#x2019;s like some sort of communication, but also an assistance to other members of the team to get the meaning of your code. After all, each programmer writes code differently than others, so making clear all the points of your code is a must-do task.</p>
<p>So, hoping that I&#x2019;ve made my point, let me carry on by saying that the proper documentation and commenting regards all programming languages and all platforms. No matter whether you write apps for iOS, web or desktop systems: The point is that you should document as you go, so it&#x2019;s easy for you (and everyone else) to revise your code really easy and without much effort.</p>
<p>As you understand, in this tutorial I am going to highlight the most important aspects of the code documentation. I&#x2019;m going to talk for both Objective-C and Swift, as there are developers writing apps in both languages, and of course I&#x2019;m planning to show you what the similarities and differences between those two languages are. Furthermore, I&#x2019;ll show you how to produce full, web-based documentation for your app, but I&#x2019;m afraid that I have to say that this is still an option for the Objective-C only.</p>
<p>As an iOS developer using the Xcode IDE, you might have been thought that the documenting possibilities would be the same for both languages. That&#x2019;s not the case though, as Swift supports too few documenting options, compared always to the Objective-C, at least at the time of the writing of this post. However, they both give you enough &#x201C;supplies&#x201D; so you can write nice documentation. We will begin with Objective-C, as there are more than enough things to say there, and we&#x2019;ll close this tutorial with code documentation in Swift. There is no need to get in more details now, as we&#x2019;ll see them in the next parts.</p>
<p>Before we begin, let me note two last things. First, I&#x2019;m not trying to make you mad about documentation, just to convince you that writing proper comments will improve your programming life. Second, writing code documentation it&#x2019;s just a habit you have to adopt, and definitely it&#x2019;s not a waste of time.</p>
<h2>Creating a Demo App in Objective-C</h2>
<p>Let&#x2019;s get started by creating a new project in Objective-C, which we will use as the testing base for what we are going to see next. If you haven&#x2019;t done yet, launch Xcode and create a new project. As we are not going to create a real demo application, selecting the <strong>Single View Application</strong> is just fine.</p>
<p>In the next step, name the project <strong>DocDemoObjC</strong>, and make sure to select the <em>Objective-C</em> option in the <strong>Language</strong> drop down menu:</p>
<p><img loading="lazy" decoding="async" width="600" height="353" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_2_new_project_ObjC_2.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4764" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_2_new_project_ObjC_2.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_2_new_project_ObjC_2-510x300.png 510w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Get finished with the guide by selecting a directory in your drive to save the project.</p>
<h2>Documentation Specifics</h2>
<p>As you know, the simplest way to write a comment in both Objective-C and Swift is to use the two slashes as shown below:</p>
<pre lang="objective-c">// This is a comment.
</pre>
<p>You can (and must) place anywhere in your code comments like that, so you clarify each part of it. However, when talking about code documentation, definitely I am not talking about the above notation. It would be pointless after all to devote a whole tutorial to that only. Code documentation regards a structured way to write comments using special <strong>keywords</strong>, also named <strong>tags</strong>, and marking the comments area with special characters, so the compiler perfectly understands it. There are a few simple rules that should be followed only. The result of all that is that your documentation can be displayed in three different places:</p>
<ol>
<li>In the <strong>Quick Help Inspector</strong> of the Utilities panel.</li>
<li>In the <strong>Help Popup</strong> that is displayed when you press the Option key and click on the name of method, class or property.</li>
<li>In the code-completion popup.</li>
</ol>
<p>Additionally, proper code documentation enables you to produce complete HTML documentation for your app using various tools, such as the <a href="https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/HeaderDoc/intro/intro.html?ref=appcoda.com">HeaderDoc</a> and <a href="http://www.stack.nl/~dimitri/doxygen/?ref=appcoda.com">Doxygen</a>. We&#x2019;ll talk about both of them later, and we&#x2019;ll see how you can do what I just said.</p>
<p>With all the above in mind, it&#x2019;s time to make one more step further and say that there are three possible ways to mark a documentation area when writing code in Objective-C:</p>
<ol>
<li>To include your comments in a /** &#x2013; */ block.</li>
<li>To include your comments in a /*! &#x2013; */ block.</li>
<li>To begin each commented line with three slashes: ///</li>
</ol>
<p>In our examples in this tutorial we are going to use the second way to write our documentation. I&#x2019;m choosing this way for two reasons: First, it&#x2019;s the only one recognised by HeaderDoc, and if the comment blocks don&#x2019;t begin with that, no help pages will be created. At second, even though Doxygen prefers the first way, it also recognises this too. So, it&#x2019;s going to suit us in both cases. The third commenting style is usually used when documenting single lines, such as properties, but still, we&#x2019;re going to stick to the second option.</p>
<p>Now, there are specific keywords (or tags) you can use when writing documentation. Tags are divided in two categories: The first one regards <em>top level</em> tags, which they can be used to specify what kind of code exactly is commented, such as classes, structs, files, etc. Note that top level tags are not required to be used, but definitely help exporting tools (such as HeaderDoc and Doxygen) to create better results. In the second category exist the <em>second level</em> tags, which specify each details for each part of the documentation block. This kind of tags is actually what you need, as each one of them define another documentation part.</p>
<p>Right next I give you the most important second level tags, but note that they&#x2019;re not just them. We&#x2019;ll see a few top level tags later. What I list is what is mostly used:</p>
<ul>
<li><strong>@brief</strong>: Use it to write a short description about the method, property, class, file, struct, or enum you&#x2019;re documenting. No line breaks are allowed.</li>
<li><strong>@discussion</strong>: Use it to write a thorough description. You can add line breaks if needed.</li>
<li><strong>@param</strong>: With this you can describe a parameter of a method or function. You can have multiple such tags.</li>
<li><strong>@return</strong>: Use it to specify the return value of a method or function.</li>
<li><strong>@see</strong>: Use it to indicate other related method or functions. You can have multiple such tags.</li>
<li><strong>@sa</strong>: Similar to the previous one.</li>
<li><strong>@code</strong>: With this tag, you can embed code snippets in the documentation. When viewing the documentation in Help Inspector, the code is represented with a different font, inside a special box. Always use the <strong>@endcode</strong> tag when you finish writing code.</li>
<li><strong>@remark</strong>: Use it to highlight any special facts about the code you&#x2019;re currently documenting.</li>
</ul>
<p>You can find a full list of all supported tags <a href="https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/HeaderDoc/tags/tags.html?ref=appcoda.com">here</a>.</p>
<p>Note that the <strong>@</strong> character is a prefix to each tag. Also, you can use special <em>switches</em> inside text, so you change its style and formatting. For example, the <em><b>Text</b></em> will make the <em>Text</em> word bold, while the <em><i>Text</i></em> will make the <em>Text</em> italic. It&#x2019;s also interesting that you can represent part of the text as code (not a code snippet), if you write <em>@cText</em>. This will result to a different font formatting when the help is displayed in Xcode.</p>
<p>Alternatively to the above, you can replace the <em>@</em> symbol with the backslash (<em>\</em>). That way the tags will be represented like this: \brief, \param, \return, etc. Note that the backslash is mostly used by the Doxygen documenting system, while the <em>@</em> is used by the HeaderDoc. Here we&#x2019;ll use everywhere the <em>@</em>, as it&#x2019;s compatible with both documenting systems.</p>
<h2>Code Documentation in Objective-C</h2>
<p>Let&#x2019;s see now how everything I mentioned above is used. Open the <em>ViewController.m</em> file, and in the private section of the class add the next property:</p>
<pre lang="objective-c">@interface ViewController ()

@property (nonatomic, strong) NSString *myName;

@end
</pre>
<p>Now, document it as shown next:</p>
<pre lang="objective-c">/*! @brief This property knows my name. */
@property (nonatomic, strong) NSString *myName;
</pre>
<p>Go then to the <em>viewDidLoad</em> method, and start typing it. You will see that in the code completion popup the description we just wrote is there!</p>
<p><img loading="lazy" decoding="async" width="463" height="137" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_3_myname_code_completion.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4765"></p>
<p>But not only. While holding down the Option key in your keyboard, click on the <em>myName</em> property name to let the help popup come up:</p>
<p><img loading="lazy" decoding="async" width="600" height="152" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_4_myname_help_popup.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4766"></p>
<p>Even more, if you open the Help Inspector in the Utilities panel, you&#x2019;ll find the same documentation there too:</p>
<p><img loading="lazy" decoding="async" width="257" height="154" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_5_myname_help_inspector.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4767"></p>
<p>Note that in the above comment the <em>@brief</em> tag could be omitted without any problem at all, as it&#x2019;s inferred. That means that the next comment is valid as well:</p>
<pre lang="objective-c">/*! This property knows my name. */
@property (nonatomic, strong) NSString *myName;
</pre>
<p>Also, the next notation is equal too:</p>
<pre lang="objective-c">/** This property knows my name. */
@property (nonatomic, strong) NSString *myName;
</pre>
<p>And this is also equal:</p>
<pre lang="objective-c">/// This property knows my name. */
@property (nonatomic, strong) NSString *myName;
</pre>
<p>Let&#x2019;s see a first, easy example on how to document methods. At this point you must acknowledge that if your goal is to produce an HTML documentation, then only the documentation in the public methods (the header .h files) is visible. Whatever you write in the private parts of your classes is still visible in Xcode help, but no implementation is exported to the documentation. So, knowing that, let&#x2019;s define a public method in the <em>ViewController.h</em> file:</p>
<pre lang="objective-c">@interface ViewController : UIViewController

-(float)toCelcius:(float)fromFahrenheit;

@end
</pre>
<p>Obviously, this method is going to convert the given Fahrenheit degrees to Celsius. Let&#x2019;s add its documentation now:</p>
<pre lang="objective-c">/*!
    @brief It converts temperature degrees from Fahrenheit to Celsius scale.

    @discussion This method accepts a float value representing the temperature in <b>Fahrenheit</b> scale and it converts it to the <i>Celsius</i> scale.

                To use it, simply call @c[self toCelsius: 50];

    @param  fromFahrenheit The input value representing the degrees in the Fahrenheit scale.

    @return float The degrees in the Celsius scale.
 */
-(float)toCelcius:(float)fromFahrenheit;
</pre>
<p>Note that above we use the <em><b></b></em> and <em><i></i></em> HTML switches to make the included words bold and italic respectively. Also notice how we mark the inline code using the <em>@c</em> switch.</p>
<p>To see in the Xcode help how that documentation looks, open the <em>ViewController.m</em> file and define the method:</p>
<pre lang="objective-c">-(float)toCelcius:(float)fromFahrenheit{
    return (fromFahrenheit - 32) / 1.8;
}
</pre>
<p>Then place the caret on the method&#x2019;s name, and look in the Quick Help Inspector:</p>
<p><img loading="lazy" decoding="async" width="255" height="386" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_6_method1_help_inspector1.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4769" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_6_method1_help_inspector1.png 255w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_6_method1_help_inspector1-198x300.png 198w" sizes="(max-width: 255px) 100vw, 255px"></p>
<p>You see that Xcode properly formats each part of the documentation. Here&#x2019;s the same in the help popup (Option + Click on the method&#x2019;s name):</p>
<p><img loading="lazy" decoding="async" width="526" height="239" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_7_method1_help_popup.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4770"></p>
<p>If you call it in the <em>viewDidLoad</em> method, then you can see the brief description in the code-completion popup:</p>
<p><img loading="lazy" decoding="async" width="540" height="170" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_8_method1_call.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4771"></p>
<p>Great, isn&#x2019;t it? Just imagine how helpful and self-explaining your code can be that way, especially if you&#x2019;re working with other people in a team.</p>
<p>To make this example even more interesting, let&#x2019;s add one more public method that will do the exact opposing thing: Conversion from Celsius to Fahrenheit. Open the <em>ViewController.h</em> file, and add the next method declaration, along with its documentation:</p>
<pre lang="objective-c">/*!
    @brief It converts temperature degrees from Celsius to Fahrenheit scale.

    @param  fromCelcius The celsius degrees value.

    @return float The degrees in the Fahrenheit scale.

    @code
        float f = [self toCelsius:80];
    @endcode

    @remark This is a super-easy method.
 */
-(float)toFahrenheit:(float)fromCelcius;
</pre>
<p>In the above snippet we added two new tags: The <em>@code &#x2013; @endcode</em> pair, and the <em>@remark</em>. You&#x2019;ll see how they&#x2019;re displayed right next.</p>
<p>Let&#x2019;s go to implement the method in the <em>ViewController.m</em> file:</p>
<pre lang="objective-c">-(float)toFahrenheit:(float)fromCelcius{
    return fromCelcius * 1.8 + 32;
}
</pre>
<p>And let&#x2019;s see the Help Popup now:</p>
<p><img loading="lazy" decoding="async" width="524" height="236" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_9_method2_help_popup.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4772"></p>
<p>Pretty nice! Now your documentation has nothing to be jealous of the Xcode default documentation.</p>
<p>Before we move to the next part, open the <em>ViewController.h</em> file, and add the following property declaration (commented of course):</p>
<pre lang="objective-c">/*! An application delegate object. */
@property (nonatomic, strong) AppDelegate *appDelegate;
</pre>
<p>Along with it, import the <em>AppDelegate</em> class:</p>
<pre lang="objective-c">#import <appdelegate.h>
</appdelegate.h></pre>
<p>The reason we added the above property to the class is to make us able to see later how it is exported using the documentation tools (HeaderDoc and Doxygen), along with the methods we already created.</p>
<h2>Files, Classes, Structs and Enums</h2>
<p>In the previous part we went through the basic documenting principles that you should be aligned with when writing properties or methods/functions. I intentionally chose to begin demonstrating from that point, as the most of your developing time will be consumed there. Now that we&#x2019;ve seen some of the essentials of our topic, let&#x2019;s keep going by taking a look on how to add documentation notes regarding files, classes, structs and enums.</p>
<p>Let&#x2019;s get started by files, and how you write informative documentation in Objective-C. When sharing programming work with others, or you distribute your code as an open source component, then adding file documentation is almost mandatory, as that&#x2019;s the best place to provide specific information to your partners or users of your code. Normally, you are going to give extra attention to the header file (.h) and the descriptions in it, as this is the one in the final documentation that will be exported (not in Xcode); however this doesn&#x2019;t mean that you should not add description to implementation files. Don&#x2019;t forget that when a project opens in Xcode, everything it&#x2019;s there, not just the header files, so make sure you don&#x2019;t leave any part of it undocumented. Besides that, implementation is not shown in exported documentation, but the description of all files is always visible.</p>
<p>Let me introduce you a few new tags that you can use when documenting a file:</p>
<ul>
<li><strong>@file</strong>: Use this tag to indicate that you&#x2019;re documenting a file (header or not). If you&#x2019;re about to use Doxygen to produce documentation, then you&#x2019;d better set the file name right after this tag. It&#x2019;s a top level tag.</li>
<li><strong>@header</strong>: Similar to the above, but used with HeaderDoc. Don&#x2019;t use the above if you won&#x2019;t use Doxygen.</li>
<li><strong>@author</strong> Use it to write the author info of the file.</li>
<li><strong>@copyright</strong>: Add copyright info.</li>
<li><strong>@version</strong>: Use it to write the current version of the file. Pretty important if versioning matters during the project&#x2019;s lifetime.</li>
</ul>
<p>There are more tags of course you could use, but those are the most usual ones. I would advice you to go either through the HeaderDoc or the Doxygen documentation, so you can find extra keywords to use if you want so.</p>
<p>Let&#x2019;s go to add documentation now to the <em>ViewController.h</em> header file. Go to the top of the file, right before the <em>import</em> command. There, add the next lines:</p>
<pre lang="objective-c">/*!
 @header ViewController.h

 @brief This is the header file where my super-code is contained.

 This file contains the most importnant method and properties decalaration. It&apos;s parted by two methods in total, which can be used to perform temperature conversions.

 @author Your_Name
 @copyright  2015 Your_Name
 @version    15.12.7
 */
</pre>
<p>You can replace the Your_Name string with your actual name, or your company&#x2019;s name. Also, it&#x2019;s always a good idea to use the <em>brief</em> tag instead of just omitting it, as this will enable the documenting systems (you&#x2019;ll see later in HeaderDoc and Doxygen) to display the short description you add here in the output HTML pages. I remind you once again that instead of the &#x201C;@&#x201D; symbol, you can use the backslash, but only for Doxygen. Also, we are not going to see here how the above documentation appears, but we&#x2019;ll do so a bit later when we&#x2019;ll produce HTML files.</p>
<p>All the above are great, but the truth is that the default informative comments added by Xcode in each new file you create are pretty good and enough in many cases. You would want to create a file description block when you work with other people in a team and each member must clarify the details of the file(s) he&#x2019;s in charge for, or when you&#x2019;re planning to produce complete documentation of the project using HeaderDoc or Doxygen, or lastly, when you&#x2019;re the sole developer but the project is parted by a big number of files. Anyway, it&#x2019;s up to you to decide the level of documentation you&#x2019;re willing to go up to.</p>
<p>Let&#x2019;s see now how you can document a class or a protocol. Once again, I give you the most usual tags only. Look up in the documentation for more tags.</p>
<ul>
<li><strong>@class</strong>: Use it to point the starting point of a documentation block regarding a class. It&#x2019;s a top level tag, and after it you should provide the class name.</li>
<li><strong>@interface</strong>: Same as above.</li>
<li><strong>@protocol</strong>: Just like the above two, just for protocols.</li>
<li><strong>@superclass</strong>: The superclass of the current class.</li>
<li><strong>@classdesign</strong>: Use this tag to mention any special design you follow or apply in the current class (for example, you could mention a Singleton class design, or something like this).</li>
<li><strong>@coclass</strong>: The name of another class that the current one works with.</li>
<li><strong>@helps</strong>: Name the class which the current one works as a helper for.</li>
<li><strong>@helper</strong>: Name any other class(es) that work as helpers for the current one.</li>
</ul>
<p>Actually, you will rarely need any of the above tags, except maybe for the <em>superclass</em>. The list is much longer, but I find it pointless to add more of them here. Let me underline that the tags starting from the <em>superclass</em> and below, are not recognised by Doxygen, only by HeaderDoc. Also, the Quick Help and Help Popup windows in Xcode display the values next to each tag, but not the tags themselves. So, decide if you&#x2019;re about to use them or not, always depending on whether you&#x2019;re going to use a documenting system, and which one.</p>
<p>Let&#x2019;s see an example by documenting our class in the <em>ViewController.h</em> file. Just right before the interface body opening, add these:</p>
<pre lang="objective-c">/*!
 @class ViewController

 @brief The ViewController class

 @discussion    This class was designed and implemented to help people covert temperatures between the Fahrenheit and Celsius scales.

 @superclass SuperClass: UIViewController\n
 @classdesign    No special design is applied here.
 @coclass    AppDelegate
 @helps It helps no other classes.
 @helper    No helper exists for this class. 
 */
</pre>
<p>Now, if you place the caret on the <em>ViewController</em> class name, or you Option+Click on it, you can see how the above description is shown in the Xcode Help.</p>
<p><img loading="lazy" decoding="async" width="517" height="263" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_10_class_name_help_popup.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4773"></p>
<p>As you see the tags are not displayed, but in this case it doesn&#x2019;t consist of a problem.</p>
<p>It&#x2019;s also great that you can see the class short description as you declare objects of it. To really watch this, open the <em>ViewController.m</em> file and go straight ahead in the <em>viewDidLoad</em> method. In there, start typing so you declare a local <em>ViewController</em> object. You&#x2019;ll see the short description of the file appearing in the code completion popup window:</p>
<p><img loading="lazy" decoding="async" width="436" height="168" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_11_viewcontroller_declare_code_completion.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4774"></p>
<p>In the same way as above you can document a protocol. Add the next lines before the class in the <em>ViewController.h</em> file:</p>
<pre lang="objective-c">/*!
    @protocol ViewControllerDelegate

    @brief The ViewControllerDelegate protocol

    It&apos;s a protocol used as a demo here. In a real application it would be quite useful.
 */
@protocol ViewControllerDelegate

/*!
    Nothing to say here... Just testing documentation.
 */
-(void)thisIsADelegateMethod;

@end
</pre>
<p>Option+Click on the protocol&#x2019;s name to see it appearing in the Help Popup window.</p>
<p><img loading="lazy" decoding="async" width="600" height="195" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_12_protocol_help_popup.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4775"></p>
<p>As you can see above, we also declared a delegate method. You might think at the moment that is meaningless, however I purposely want this method to be there for demo reasons only; when we&#x2019;ll use HeaderDoc and Doxygen to export documentation later it will be nice to see it in the exported HTML pages.</p>
<p>Now that we&#x2019;ve talked about files, classes and protocols, and you have hopefully got the big picture, let&#x2019;s see a couple more special cases: How to document structs and enumerations. Their common element is that you use the <em>@typedef</em> top level tag in both of them, so you indicate the opening of the documentation block (I remind you that using top level tags is absolutely optional).</p>
<p>For Doxygen specifically, you should use the <em>@struct</em> tag for structs, and the <em>@enum</em> tag for enums, instead of the <em>@typedef</em>.</p>
<p>Let&#x2019;s see the following code struct. Add it to the <em>ViewController.h</em> file right before the opening line of the interface:</p>
<pre lang="objective-c">typedef struct {
    int sun;
    int clouds;
    int rain;
    int snow;
} WeatherConditionsInDays;
</pre>
<p>Now add these few lines above it:</p>
<pre lang="objective-c">/*!
 @typedef WeatherConditionsInDays

 @brief  A struct about the weather.

 @discussion
 The values of this structure represent how many sunny, cloudy, rainy, and snowy days existed over the last year. If this was a real app, they could be perfectly used.

 @field sun Good weather
 @field clouds  Where&apos;s the sun?
 @field rain    Get an umbrella
 @field snow    Watch out... A snowball is coming!
 */
</pre>
<p>As you see here, there&#x2019;s a new tag named <em>@field</em>. This tag is handy to describe each single variable of the struct. Again, I must highlight the difference between the HeaderDoc and Doxygen. In HeaderDoc, this tag is acceptable and valid. However, in Doxygen things change as it&#x2019;s not compatible with this tag. What we could do in this case is to simply comment each variable separately. Doing that will also display the comment for each one when we&#x2019;ll access them in the implementation file. Let&#x2019;s see that (note that the <em>@field</em> tags and the comments above variables contain different values so it&#x2019;s easier to be identified later):</p>
<pre lang="objective-c">/*!
 @typedef WeatherConditionsInDays

 @brief  A struct about the weather.

 @discussion
 The values of this structure represent how many sunny, cloudy, rainy, and snowy days existed over the last year. If this was a real app, they could be perfectly used.

 @field sun Good weather
 @field clouds  Where&apos;s the sun?
 @field rain    Get an umbrella
 @field snow    Watch out... A snowball is coming!
 */
typedef struct {
    /*! Good weather */
    int sun;
    /*! At least it&apos;s not raining */
    int clouds;
    /*! Don&apos;t forget to get your umbrella */
    int rain;
    /*! Time to go skiiiiiing */
    int snow;
} WeatherConditionsInDays;
</pre>
<p>If you go now to the <em>ViewController.m</em> file and declare an variable of this struct, then by accessing any of the above values you&#x2019;ll see the description in the code completion popup window.</p>
<p><img loading="lazy" decoding="async" width="459" height="159" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_13_weather_sun_code_completion.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4776"></p>
<p>Enumerations are handled in the exact same way, so I leave it to you to as an exercise to create an enum type and document it. Easy task to accomplish, isn&#x2019;t it? Once your enum is ready, use it in the <em>viewDidLoad</em> method to see if your documentation is appeared in any of the Xcode Help options.</p>
<h2>Watching For Errors</h2>
<p>As you have seen in all the previous examples, next to the <em>@param</em> tag you must always write the parameter&#x2019;s name, and after that a proper description. Of course, it&#x2019;s quite possible that you mistype a parameter name, especially if it&#x2019;s a bit complex, and to create documentation containing errors. However, there&#x2019;s a way to be protected against that, and I suspect that you didn&#x2019;t know that Xcode can be your trusty assistant in that.</p>
<p>Indeed, even though Xcode deals with documentation once its written, it can help you by preventing you mistyping any parameter names. All it gets to do that, is to enable a setting. Let&#x2019;s see what I mean exactly:</p>
<p>In the Project Navigator, click on the Project&#x2019;s group, and then go straight ahead to the <strong>Build Settings</strong> tab, as shown in the next figure:</p>
<p><img loading="lazy" decoding="async" width="600" height="77" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_14_select_build_settings.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4777"></p>
<p>Once you do so, in the Search box just type the <em>comments</em> keyword and wait to see the results right below. One of the returned results is a setting named <strong>Documentation Comments</strong>, and (normally) its current value is set to <strong>NO</strong>. All you have to do is to set the <strong>YES</strong> value, and you&#x2019;re ready.</p>
<p><img loading="lazy" decoding="async" width="600" height="237" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_15_enable_documentation_settings.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4778"></p>
<p>Now, let&#x2019;s go to see how the above setting affects the way we document our code. Open the <em>ViewController.m</em> file, and go to the private class section, where we are about to declare a private method. Here it is:</p>
<pre lang="objective-c">@interface ViewController ()

-(float)showCurrentTemperatureInCity:(NSString *)targetCityName showInScale:(NSString *)preferredScale;

@end
</pre>
<p>If we were really going to implement it, this method would return the temperature in the selected city, expressed in the preferred scale (Fahrenheit or Celsius). Now, let&#x2019;s add a few comments above it:</p>
<pre lang="objective-c">/*!
    This method returns the current temperature in the selected city, expressed in either Fahrenheit or Celsious degrees.

    @param  targetcityName  The city that the temperature will be returned for.
    @param  preferredScale  Fahrenheit or Celsius.

    @return float   The current temperature of the city.
 */
-(float)showCurrentTemperatureInCity:(NSString *)targetCityName showInScale:(NSString *)preferredScale;
</pre>
<p>Once you copy-paste the above comments in your Xcode, a warning will appear in the line where the first parameter is documented, telling us that the <em>targetcityName</em> parameter was not found in the function declaration. And guess what? That&#x2019;s true! Instead of writing the parameter name properly (<em>targetCityName</em>), I wrote it wrongly by not capitalizing the first character of the &#x201C;city&#x201D; word (<em>targetcityName</em>). That&#x2019;s something that in a big project with a lot of comments we would probably not realize, but thankfully Xcode is here to give us a hand and an extra &#x201C;pair of eyes&#x201D;.</p>
<p>Now, if you click in the warning triangle icon at the left, you will notice that Xcode auto-suggests the proper parameter name, which you can click so it&#x2019;s fixed. Alternatively, go and fix it on your own.</p>
<p><img loading="lazy" decoding="async" width="600" height="107" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_16_fix_param_name_error.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4780"></p>
<p>With all the above, you don&#x2019;t need to be afraid of making any typo while writing parameter names during documentation.</p>
<h2>Producing Documentation With HeaderDoc</h2>
<p>Now that we have covered the essentials about code documentation, let&#x2019;s move to another important part, and let&#x2019;s see how we can create HTML files containing the documentation we added to our project. In this section we are going to use HeaderDoc, a pretty nice tool that works great with the documentation written to files. For your reference, I recommend you visit <a href="https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/HeaderDoc/intro/intro.html?ref=appcoda.com">this site</a> and read more about it. In short, I&#x2019;m just telling you that using HeaderDoc we&#x2019;re going to export all the documented parts of the project in HTML pages. In small projects doing that might be meaningless, but in large projects or in cases where you deliver your own SDK to others, an accompanying documentation is almost necessary.</p>
<p>The HeaderDoc tool is actually a command-line tool. It supports various switches to configure the exporting process in a high-detail level, and you can find them in the link I gave you above. Here, we&#x2019;re going to use just one switch, useful to specify the output directory (the directory where the documentation will reside).</p>
<p>Let&#x2019;s see some action now. Initially, let&#x2019;s create a directory for the documentation that will be produced. For easy access, I&#x2019;m choosing to do that in my Desktop, but you can select any other destination you desire, as long as you update the paths you&#x2019;ll see later on. So, in my Desktop I created a directory named <strong>DocDemo</strong>, and in there I added two subdirectories: One named <strong>HeaderDoc</strong>, and one named <strong>Doxygen</strong>. As you guess, the documentation produced by each tool will be placed to the respective folder.</p>
<p><img loading="lazy" decoding="async" width="406" height="73" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_17_output_dirs.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4781"></p>
<p>Next, you must open the <strong>Terminal</strong> app, so either click on the <strong>LaunchPad &gt; Other group &gt; Terminal</strong>, or in the <strong>Spotlight</strong> write the <em>terminal</em> term.</p>
<p><img loading="lazy" decoding="async" width="600" height="384" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_18_spotlight_terminal.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4782" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_18_spotlight_terminal.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_18_spotlight_terminal-469x300.png 469w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Now, it would be a nice idea to navigate yourself in the project directory using terminal, and you can do that easily following the next steps:</p>
<ol>
<li>In Terminal write the <em>cd</em> command and hit the spacebar. Don&#x2019;t press the Return key.</li>
<li>In Finder, locate the root directory that contains the project.</li>
<li>Drag and drop this directory straight to the terminal window, as you see in the next screenshot.</li>
</ol>
<p><img loading="lazy" decoding="async" width="600" height="391" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_19_drag_drop_dir.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4783" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_19_drag_drop_dir.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_19_drag_drop_dir-460x300.png 460w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Then hit the Return key in the keyboard, and to verify that you&#x2019;re in the right folder just use the <em>pwd</em> command (in terminal always).</p>
<p>The HeaderDoc command we&#x2019;ll use here is named <strong>headerdoc2html</strong>, and we&#x2019;ll form it as follows:</p>
<pre lang="Shell" nums="false">headerdoc2html -o OutputDirectory InputDirectory
</pre>
<p>The <em>OutputDirectory</em> is the directory we created right before, and the input directory is the folder where the project files exist.</p>
<p>Now, let&#x2019;s use it in real. In your terminal window, write or copy-paste the following part:</p>
<pre lang="Shell" nums="false">headerdoc2html -o 
</pre>
<p>Note that after the <em>-o</em> switch there&#x2019;s a space character.</p>
<p>Next, go in Finder and click on the directory name where the documentation will be exported. Following the steps described above, drag and drop it to the terminal. After that, type the name of the input directory followed by a slash. Here&#x2019;s how the whole command should look like:</p>
<pre lang="Shell" nums="false">headerdoc2html -o /Users/gabriel/Desktop/DocDemo/HeaderDoc DocDemoObjC/
</pre>
<p><img loading="lazy" decoding="async" width="450" height="281" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_20_terminal_final.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4784"></p>
<p>You will see various stuff appearing, but no need to pay special attention to that right now. Once it gets finished, mark and copy the path of the output directory, write the next command in terminal:</p>
<pre lang="Shell" nums="false">gatherheaderdoc 
</pre>
<p>and paste the path. Press Return and let it run. This command will create a table of contents page, where all commented files, classes and methods will exist in one place.</p>
<p>That&#x2019;s it. Now go to Finder, and open the <strong>masterTOC.html</strong> file in your browser. Here&#x2019;s what you&#x2019;ll see:</p>
<p><img loading="lazy" decoding="async" width="600" height="267" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_21_toc.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4785"></p>
<p>If you click in the <em>ViewController</em> link, here&#x2019;s the page that you&#x2019;ll be guided to:</p>
<p><img loading="lazy" decoding="async" width="600" height="430" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_22_view_controller_page.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4786" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_22_view_controller_page.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_22_view_controller_page-419x300.png 419w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>There you can find the description of the file, and the class, the protocol and the struct with links to them along with their brief descriptions. The struct details are shown in the same page.</p>
<p><img loading="lazy" decoding="async" width="600" height="430" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_23_struct_doc_page.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4787" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_23_struct_doc_page.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_23_struct_doc_page-419x300.png 419w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Notice that the fields contain double values, but that&#x2019;s only because we added comments both using the <em>@field</em> tag, and above each struct variable. If you want, you can go back in Xcode and delete any of the two. Next, run again the HeaderDoc commands in terminal and get back here.</p>
<p>If you click in the class link, you&#x2019;ll go to a new page, where you can see its description, the two methods and the one property we declared in the header file.</p>
<p><img loading="lazy" decoding="async" width="600" height="430" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_24_class_page.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4788" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_24_class_page.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_24_class_page-419x300.png 419w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Now that you&#x2019;ve seen the results, walk freely around everywhere in the documentation pages and see how everything is being displayed. HeaderDoc usage doesn&#x2019;t stop here, but that&#x2019;s what you&#x2019;ll need in most of the cases.</p>
<h2>Producing Documentation with Doxygen</h2>
<p>Time to leave HeaderDoc behind us and let&#x2019;s see how to use a quite widespread documenting system, named <strong>Doxygen</strong>. Before we see the details concerning it, I should say that Doxygen was not originally designed to parse documentation in Objective-C. However, it is going to perfectly work as it aims to C and C++ style languages mostly, and as you&#x2019;ll see by yourself, it supports a variety of languages. Besides that, it contains a large amount of documenting tags, and if you decide to write documentation that will eventually be parsed by Doxygen, you can use any of them so as to have greater compatibility.</p>
<p>Doxygen is a third-party application which you must download before use it. There are versions of it for all common operating systems, so it can work for you even if you&#x2019;re not developing for iOS only. At this point, let me give you three important links:</p>
<ol>
<li><a href="http://www.stack.nl/~dimitri/doxygen/manual/docblocks.html?ref=appcoda.com">In this link</a> you can find all the resources you need regarding the code documentation.</li>
<li><a href="http://www.stack.nl/~dimitri/doxygen/manual/commands.html?ref=appcoda.com">Here</a> you can find all the tags supported by Doxygen, and by clicking to each one you get extra information about its usage.</li>
<li>Lastly, you can visit <a href="http://www.stack.nl/~dimitri/doxygen/download.html?ref=appcoda.com">this</a> page to download the Doxygen application.</li>
</ol>
<p>Before we download it, let me note that you can find much more than what I just mentioned above in the Doxygen website. Actually, as you can see in the next screenshot, there&#x2019;s a menu panel at the left side, which you can use to dive in various parts of it and find numerous details and how-tos.</p>
<p><img loading="lazy" decoding="async" width="600" height="430" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_25_doxygen_menu.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4789" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_25_doxygen_menu.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_25_doxygen_menu-419x300.png 419w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Now, pay a visit to the last link I gave you above, and scroll a bit down to the page until you find an area named <strong>A binary distribution for Mac OS X 10.5 and later</strong>. Click either in the <em>ftp</em>, or in the <em>http</em> link to initiate the package downloading. Depending on your Internet connection speed, it might take a few seconds for the download to complete, as the file is about 55 Mb.</p>
<p>Once the download process is over, open the package. Then, get the Doxygen application and drag it to your <em>Applications</em> directory.</p>
<p>If you don&#x2019;t want to add it to the Applications directory it&#x2019;s okay. Just place it anywhere else you want. After all, Doxygen is a fully self-contained application, so to remove it just delete its app file, no matter where you&#x2019;ll place it.</p>
<p>Assuming now that you&#x2019;ve copied it in the Applications directory, click in the Launchpad to find it easily. Click it to let it run.</p>
<p><em>NOTE: If you get a message saying that the application cannot be opened because it&#x2019;s from an unidentified developer, follow the next steps to overcome it: In Finder, open the Applications directory. Locate the Doxygen app, and then Ctrl+Click it. Select the <strong>Open</strong> option in the context menu, and in the new dialog window that will be shown, click to the <strong>Open</strong> button.</em></p>
<p>Now, leave the Doxygen app aside, and go back to Xcode. We&#x2019;ll perform two changes in two tags, so everything to be recognised. Make sure to open the <em>ViewController.h</em> file, and in its description block replace the <strong>@header</strong> top level tag with the <strong>@file</strong> tag. Also, a modification is needed to the documentation block of the struct, where the <strong>@typedef</strong> tag must be replaced with the <strong>@struct</strong> tag. After having done these, let&#x2019;s leave Xcode again.</p>
<p>If you&#x2019;ve used Doxygen in the past, then you definitely know what to do. However, I&#x2019;ll assume it&#x2019;s your first time in this app, so let me present you the most important steps.</p>
<p>Right next it&#x2019;s the initial Doxygen window upon first run:</p>
<p><img loading="lazy" decoding="async" width="600" height="492" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_28_doxygen_initial.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4790" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_28_doxygen_initial.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_28_doxygen_initial-366x300.png 366w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Before I tell you the exact settings you should apply, it&#x2019;s necessary to say that Doxygen provides two modes of usage: The <strong>Wizard</strong> which consists of a simple and general way, and the <strong>Expert</strong> mode, where a huge number of settings can be specified so you customize each detail of the produced documentation.</p>
<p>I&#x2019;m not going to focus on the <em>Expert</em> mode, because the applied settings there are highly depending on the personal needs of each developer. That means that we&#x2019;ll stick with the <em>Wizard</em> mode, but prior to this, I think that it worths to take a super-fast walk in the <em>Expert</em> mode. By clicking in the <strong>Expert</strong> button in the main window area, you instantly see that you are given with a great number of settings in the main panel. You can scroll up and down to go trough all of them, but they&#x2019;re not just them. At the left side, there&#x2019;s a smaller panel titled <strong>Topics</strong>, and by clicking to another topic you access its own settings. If you have the time, visit all of them. You might find useful options that you would like to use in your apps.</p>
<p>Now, let&#x2019;s focus in the <em>Wizard</em> mode. Make sure to click on the respective button, so you can follow what I describe next. At first, at the top of the window we must specify where Doxygen runs from. Just click in the <strong>Select</strong> button, and select the Applications directory in your computer, or any other location where you&#x2019;ve copied the Doxygen app into.</p>
<p>Next, let&#x2019;s specify the project&#x2019;s name. In the <strong>Project Name:</strong> field, set the <strong>DocDemo in Objective-C</strong> value (or anything else you desire). If you want, also fill the next fields in too. Below that, we must specify the path to our project. Once again, use the <strong>Select</strong> button and navigate yourself to the root directory of the project. It would be a good idea to click in the <strong>Scan recursively</strong>, so Doxygen can scan subdirectories too.</p>
<p>Lastly, specify where the produced documentation should be stored. If you remember, we had created the <strong>Doxygen</strong> subdirectory in the <strong>DocDemo</strong> directory in Desktop for this purpose. So, click on the Select button next to the Destination Directory field, and pick it. </p>
<p><img loading="lazy" decoding="async" width="600" height="492" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_31_doxygen_project_settings.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4793" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_31_doxygen_project_settings.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_31_doxygen_project_settings-366x300.png 366w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Next, in the <strong>Topics</strong> list at the left, click on the <strong>Mode</strong> option. In the new settings, click in the <strong>All Entities</strong> option:</p>
<p><img loading="lazy" decoding="async" width="600" height="492" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_32_document_mode_settings.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4794" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_32_document_mode_settings.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_32_document_mode_settings-366x300.png 366w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Next, again in the <strong>Topics</strong> list, click on the <strong>Output</strong> option. Here you can find various exporting options. Feel free to select any kind of output you desire. For this example, I deselected the <em>LaTeX</em> option, I just left the <em>HTML</em> on.</p>
<p><img loading="lazy" decoding="async" width="600" height="492" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_33_doxygen_output_settings.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4795" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_33_doxygen_output_settings.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_33_doxygen_output_settings-366x300.png 366w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Finally, in the <strong>Diagrams</strong> options you can just leave the default setting as they are.</p>
<p>It&#x2019;s time now to produce the documentation. Please, be sure that you&#x2019;ve set all the options mentioned above before you continue. You did it? Okay, let&#x2019;s keep going. Click on the <strong>Run</strong> button (next to the Wizard and Expert buttons), and in the main window area now you will see a new button titled <strong>Run doxygen</strong>. Click it to let the app start creating the HTML files for you. In the white area you&#x2019;ll see some output messages, and if something is wrong, that&#x2019;s the place where you&#x2019;ll see it.</p>
<p>Anyway, once it&#x2019;s finished, open Finder and navigate straight ahead to the output directory to see the exported files. You will notice that a bunch of files have been created, and the one you&#x2019;re looking for is named <strong>index.html</strong>. Double click it to open it in the browser. Alternatively, if you don&#x2019;t care to see the exported files, simply click on the <strong>Show HTML output</strong> in the Doxygen window.</p>
<p>This is the first screen you face by opening the index page:</p>
<p><img loading="lazy" decoding="async" width="600" height="430" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_34_doc_index_page.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4796" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_34_doc_index_page.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_34_doc_index_page-419x300.png 419w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>It just contains the project title we set earlier, the generation timestamp, and a couple of links at the top. Use these links to navigate yourself around. For example, if you click on the <strong>Classes</strong> link, you&#x2019;ll get a list of all classes existing in the project. The interesting part here is that next to each class they are displayed the brief descriptions we wrote (only where we wrote them).</p>
<p><img loading="lazy" decoding="async" width="600" height="430" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_35_doc_classes.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4797" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_35_doc_classes.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_35_doc_classes-419x300.png 419w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Here&#x2019;s what you see when tapping in the <em>ViewController</em> class:</p>
<p><img loading="lazy" decoding="async" width="600" height="430" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_36_doc_viewcontroller_class.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4798" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_36_doc_viewcontroller_class.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_36_doc_viewcontroller_class-419x300.png 419w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>As you can see, the detailed documentation of the methods and the one public property we have in the project can be found there. Another interesting point is under the <strong>Files</strong> menu, where all the parsed files are listed, and by selecting the <em>ViewController.h</em> file. In there you find the file description, and everything we declared: The class, the protocol and the struct.</p>
<p><img loading="lazy" decoding="async" width="600" height="430" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_37_doc_file_viewcontroller.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4799" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_37_doc_file_viewcontroller.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_37_doc_file_viewcontroller-419x300.png 419w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Use the <em>More&#x2026;</em> links to go to the details of any of the above. There&#x2019;s also a link titled <em>&#x201D;Go to the source code of this file.&#x201D;</em>, which if it&#x2019;s tapped, it displays the code of the <em>ViewController.h</em> header file. Note that whatever is written in header files is public, so it can be displayed here. However, don&#x2019;t expect to find any implementation code at all. That&#x2019;s for &#x201C;your eyes only&#x201D;.</p>
<p><img loading="lazy" decoding="async" width="600" height="430" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_38_doc_file_code.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4800" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_38_doc_file_code.png 600w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_38_doc_file_code-419x300.png 419w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>So, I&#x2019;m pretty sure at this point that you&#x2019;ve got the grasp of all the above. Navigate in the exported HTML pages, go back in Xcode to make changes in documentation, and re-produce everything. Also, don&#x2019;t hesitate to set advanced settings and see what happens. In general, play around as much as you want, and familiarize yourself with Doxygen. It&#x2019;s a great tool that can be used for both small and big projects.</p>
<h2>Creating a Demo App in Swift</h2>
<p>Let&#x2019;s turn page now for one more time, and let&#x2019;s say a few words about documenting your code in Swift. To make things as much clear as possible, let&#x2019;s create a new demo project, this time in Swift.</p>
<p>So, begin creating one in Xcode, and in the first step of the guide specify the <strong>Single View Application</strong> as the template of the application. Next, name the project <strong>DocDemoSwift</strong>, and also be sure that the selected language is the <strong>Swift</strong>. Proceed, select a directory to save the project, and let Xcode to create it.</p>
<h2>Documenting in Swift</h2>
<p>Code documentation in Swift is less powerful that in Objective-C, and that&#x2019;s the reason I left the discussion about it for the end. Unfortunately, neither HeaderDoc nor Doxygen support Swift (at least for now, I can&#x2019;t say what may happen in the future), and the documentation formatting is now based in the <strong>reStructuredText</strong>, an open source project for which you can find more info <a href="http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html?ref=appcoda.com">here</a>.</p>
<p>From all the tags we met in the previous parts of this tutorial, there are only two that can be used in this case: The <strong>param</strong> and <strong>return</strong>, which actually becomes <strong>returns</strong> (note the &#x201C;s&#x201D; at the end). Also, neither the <em>@</em> or the backslash symbol is supported. Instead, both of these tags are included in semicolons, for example <em>:param:</em>. After that, the parameter name must be written, followed by its description.</p>
<p>The <em>brief</em> and <em>discussion</em> tags are not used, but the respective parts can be added to the documentation as the tags are inferred, meaning that a short text at the beginning of the documentation block is considered to be the brief description, and bigger text parts after that are the discussion.</p>
<p>The new and interesting thing here is that in the discussion part you can add ordered and unordered lists, as well as fields with descriptions. For example, to add an ordered list you just need to write:</p>
<pre lang="objective-c" nums="false">1. First item
2. Second item
3. Third item
</pre>
<p>For unordered lists, you either use the <em>asterisk (*)</em>, or the <em>dash (-)</em> symbol. For example:</p>
<pre lang="objective-c" nums="false">* An item
* Another item
* More items
</pre>
<p>And:</p>
<pre lang="objective-c" nums="false">- An item
- Another item
- More items
</pre>
<p><em>Note: If you are familiar with the Markdown syntax, then the above are already known to you.</em></p>
<p>To have fields in the discussion area, you just have to write the field name surrounded by semicolons, and then the description:</p>
<pre lang="objective-c" nums="false">:MyField: This is a field example
</pre>
<p>All the above, including the two tags (<em>param</em> and <em>returns</em>) are enough so you write proper documentation. Even though not as many options as in Objective-C are provided, I believe that all the previous stuff is all you need, so I&#x2019;ll show you no more.</p>
<p>Let&#x2019;s go to Xcode now to see an example of all those. Open the <em>ViewController.swift</em> file, and in there define the following method (similar to the Objective-C example):</p>
<pre lang="swift">func toCelsius(fromFahrenheit: Float) -&gt; Float {
    return (fromFahrenheit - 32) / 1.8;
}
</pre>
<p>Having in mind the prior description about the documentation in Swift code, here&#x2019;s how the same comments we added in Objective-C version are written here:</p>
<pre lang="swift">/**
It converts temperature degrees from Fahrenheit to Celsius scale.

This method accepts a float value representing the temperature in Fahrenheit scale and it converts it to the Celsius scale.
To use it, simply call toCelsius(50) or self.toCelsius(50)

:param: fromFahrenheit The input value representing the degrees in the Fahrenheit scale.

:returns:   float The degrees in the Celsius scale.
*/
func toCelsius(fromFahrenheit: Float) -&gt; Float {
    return (fromFahrenheit - 32) / 1.8;
}
</pre>
<p>Note that we use the <em>/** &#x2013; */</em> notation here. By looking in the Help popup, here&#x2019;s the result:</p>
<p><img loading="lazy" decoding="async" width="565" height="295" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_40_func_help_popup_swift.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4802"></p>
<p>Also, if you start typing the method&#x2019;s name in the <em>viewDidLoad</em> method, the brief description is appeared in the code completion:</p>
<p><img loading="lazy" decoding="async" width="538" height="166" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_41_func_code_completion_swift.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4803"></p>
<p>Now, let&#x2019;s create a super-simple new method that will do nothing at all:</p>
<pre lang="swift">func myHelloMethod(){
    println(&quot;Hello there&quot;)
}
</pre>
<p>We are going to document the above method by creating lists and fields. What you&#x2019;ll see next is clearly an example, so don&#x2019;t try to find any logic in the comments.</p>
<pre lang="swift">/**
    This method was implemented to do nothing hard, just to say hello.

    Here is a demo of an ordered list:

    1. One
    2. Two
    3. Three
    4. Four

    How about an unordered list?

    * North
    * East
    * South
    * West

    Let&apos;s add a couple of fields now:

    :Job: My dreaming job
    :Salary:    My dreaming salary

*/
func myHelloMethod(){
    println(&quot;Hello there&quot;)
}
</pre>
<p>By Option+Click in the method&#x2019;s name, here&#x2019;s what is being displayed in the Help popup:</p>
<p><img loading="lazy" decoding="async" width="541" height="449" src="http://www.appcoda.com/wp-content/uploads/2015/02/t28_42_hello_method_help_popup.png" alt="Documenting Your Objective-C and Swift Code in Xcode with HeaderDoc and Doxygen" class="aligncenter size-full wp-image-4804" srcset="https://www.appcoda.com/content/images/wordpress/2015/02/t28_42_hello_method_help_popup.png 541w, https://www.appcoda.com/content/images/wordpress/2015/02/t28_42_hello_method_help_popup-361x300.png 361w" sizes="(max-width: 541px) 100vw, 541px"></p>
<p>All the above is pretty much what you need to document your code in Swift. However, don&#x2019;t hesitate to try more options after having read the <em>reStructuredText</em> manual (or some of it&#x2026; it&#x2019;s huge).</p>
<h2>Summary</h2>
<p>In this tutorial we&#x2019;ve managed to see many aspects concerning the code documentation. We talked for both Objective-C and Swift, and went through the most important principles regarding each one. As you found out, in Objective-C you have a ton more options to use, but yet, the provided tools are just fine in Swift as well. What I presented today is not what only exists. There are more you can find and use, but my point was to introduce you the most usual documenting information. What you&#x2019;ve read here, is what you&#x2019;ll need in nine out of ten cases. Also, don&#x2019;t forget the two interesting tools we met, HeaderDoc and Doxygen. Both of them can produce great documentation, and they can become nice &#x201C;friends&#x201D; of yours. As a last word, I&#x2019;d like to highlight once again that documenting your code is really a big deal. You may often doubt about that, but trust me, it worths each second you&#x2019;ll consume for this task. Help both yourself and others by writing proper documentation, straight into the point, that explains everything you do in your code. If you&#x2019;re not used to doing that, you&#x2019;d better start now, even if you&#x2019;re not a young developer. See you!</p>

<!--kg-card-end: html-->
]]></content:encoded></item><item><title><![CDATA[Creating Simple Animations with Facebook's Pop Framework]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p><strong>Editor&#x2019;s note:</strong> When Facebook released its Paper app, it generated a lot of buzz in the app world. If you&#x2019;ve used <a href="https://www.facebook.com/paper">Paper</a> before, the visual news feed reader, you should be amazed by its beautiful and fluid user interface. The design and attention to detail on</p>]]></description><link>https://www.appcoda.com/facebook-pop-framework-intro/</link><guid isPermaLink="false">66612a0f166d3c03cf01138f</guid><category><![CDATA[iOS Programming]]></category><category><![CDATA[Objective C]]></category><dc:creator><![CDATA[Hossam Ghareeb]]></dc:creator><pubDate>Mon, 22 Dec 2014 21:32:09 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2014/12/pop-animations.jpg" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://www.appcoda.com/content/images/wordpress/2014/12/pop-animations.jpg" alt="Creating Simple Animations with Facebook&apos;s Pop Framework"><p><strong>Editor&#x2019;s note:</strong> When Facebook released its Paper app, it generated a lot of buzz in the app world. If you&#x2019;ve used <a href="https://www.facebook.com/paper">Paper</a> before, the visual news feed reader, you should be amazed by its beautiful and fluid user interface. The design and attention to detail on the app is unmatched. The app refrains from using buttons and menus, but was built to be gesture-driven, to a degree that was uncommonly found in iOS apps at the time of its release. It went beyond Core Animation. The team has built its own animation engine to support all the smooth animations and coordinate animations with touch inputs. When I first tried out the app, I was wondering how some of the animations were implemented. Honestly I didn&#x2019;t know how. A couple months later, the company <a href="https://github.com/facebook/pop?ref=appcoda.com">open-sourced Pop</a>, the animation engine behind its iOS Paper app. As a Facebook&#x2019;s engineer described, Pop drives the scrolling, bouncing, and unfolding effects that bring Paper to life. Thanks to Facebook team. With the Pop framework, this means you can create similar animations that were found on Paper in your own apps.</p>
<p>The Pop framework was first released in late April, 2014. So far we haven&#x2019;t written any tutorials about the framework. Thanks to Hossam who is kind enough to share with us an introduction of POP and show us how to create a few simple animations. </p>
<p>Enter the Pop tutorial.</p>
<p><img loading="lazy" decoding="async" width="1024" height="654" src="http://www.appcoda.com/wp-content/uploads/2014/12/pop-animations.jpg" alt="Creating Simple Animations with Facebook&apos;s Pop Framework" class="aligncenter size-full wp-image-4513" srcset="https://www.appcoda.com/content/images/wordpress/2014/12/pop-animations.jpg 1024w, https://www.appcoda.com/content/images/wordpress/2014/12/pop-animations-470x300.jpg 470w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>In this tutorial, we will talk about Facebook POP framework to make great and easy animations in your own iOS apps. Like any other tutorials on AppCoda, I will help you understand and master Pop by examples. We will create four simple animations together to explore the framework.</p>
<p>Pop is an extensible animation engine for both iOS and OS X. In addition to basic animations including Linear, Ease-In, Ease-Out, Ease-In-Ease-Out animations, it supports spring (at the time of its release, spring animation was not supported in iOS), decay and custom animations:</p>
<ul>
<li>Spring &#x2013; dynamic animation that creates a nice bouncing effect.</li>
<li>Decay &#x2013; dynamic animation that brings a movement to a smooth halt.</li>
<li>Custom &#x2013; because the engine is designed to be extensible, you can create your own custom animations.</li>
</ul>
<p>The fundamental animation type of Pop is a POPAnimation. You can think of it as the abstract or base class of all POP animations. The Pop interface is implemented as an addition of category on NSObject. This allows any object to be animated.</p>
<p><img loading="lazy" decoding="async" width="1024" height="677" src="http://www.appcoda.com/wp-content/uploads/2014/12/pop-category.jpg" alt="Creating Simple Animations with Facebook&apos;s Pop Framework" class="aligncenter size-full wp-image-4511" srcset="https://www.appcoda.com/content/images/wordpress/2014/12/pop-category.jpg 1024w, https://www.appcoda.com/content/images/wordpress/2014/12/pop-category-454x300.jpg 454w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>The Pop API is very developer friendly that lets you easily build some realistic, physics-based interactions. For instance, here is the code snippet for creating a spring animation on a text label:</p>
<pre lang="objective-c">
POPSpringAnimation *sprintAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPViewScaleXY];
sprintAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(0.9, 0.9)];
sprintAnimation.velocity = [NSValue valueWithCGPoint:CGPointMake(2, 2)];
sprintAnimation.springBounciness = 20.f;
[self.textLabel pop_addAnimation:sprintAnimation forKey:@&quot;springAnimation&quot;];
</pre>
<p>Easy, right? Let&#x2019;s get started and create the demo app. I&#x2019;m sure you&#x2019;ll have a better understanding of Pop after going through the project.</p>
<h2>Using Pop Framework</h2>
<p>If you use CocoaPods, you can just add the following to your project Podfile:</p>
<p>pod &#x2018;pop&#x2019;, &#x2018;~&gt; 1.0&#x2019;</p>
<p>For non-CocoaPods project, you can <a href="https://github.com/facebook/pop?ref=appcoda.com">download the Pop framework here</a> and add the &#x201C;pop&#x201D; folder to your workspace. Go to your project and ensure the &#x201C;Other Linker Flags&#x201D; option is added with -lc++ under Build Settings. </p>
<p><img loading="lazy" decoding="async" width="1024" height="596" src="http://www.appcoda.com/wp-content/uploads/2014/12/using-pop-framework-hd.jpg" alt="Creating Simple Animations with Facebook&apos;s Pop Framework" class="aligncenter size-full wp-image-4507" srcset="https://www.appcoda.com/content/images/wordpress/2014/12/using-pop-framework-hd.jpg 1024w, https://www.appcoda.com/content/images/wordpress/2014/12/using-pop-framework-hd-515x300.jpg 515w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>Also set the Header Search Path to the correct folder. For instance, I used to put the &#x201C;pop&#x201D; framework under a &#x201C;Library&#x201D; folder. You can set the Header Search Path to &#x201C;$(SRCROOT)/Library&#x201D;. To use the framework, you can just add the following import statement in your source code:</p>
<pre lang="objective-c">
#import <pop pop.h>
</pop></pre>
<p>Once you added the framework, create a simple table view like below. It&#x2019;s just a simple table displaying three rows:</p>
<p><img loading="lazy" decoding="async" width="320" height="640" src="http://www.appcoda.com/wp-content/uploads/2014/12/sample-pop-app.jpg" alt="Creating Simple Animations with Facebook&apos;s Pop Framework" class="aligncenter size-full wp-image-4480" srcset="https://www.appcoda.com/content/images/wordpress/2014/12/sample-pop-app.jpg 320w, https://www.appcoda.com/content/images/wordpress/2014/12/sample-pop-app-150x300.jpg 150w" sizes="(max-width: 320px) 100vw, 320px"></p>
<p>If you don&#x2019;t want to start from scratch, you can <a href="https://www.dropbox.com/s/iqkp1d3uhbh2hd4/POPDemoStarter.zip?dl=0&amp;ref=appcoda.com">download the starter project here</a>. </p>
<h2>Example #1: UITableViewCell Animation</h2>
<p>For the first example, we will create animations on the table view cells. We will add a basic scale up animation when a user highlights a cell. When releasing, we will scale it back using spring animation.</p>
<p>Go to ExampleCell.m and override the setHighlighted: method using the code snippet below:</p>
<pre lang="objective-c">
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
    [super setHighlighted:highlighted animated:animated];
    if (self.highlighted) {
        POPBasicAnimation *scaleAnimation = [POPBasicAnimation animationWithPropertyNamed:kPOPViewScaleXY];
        scaleAnimation.duration = 0.1;
        scaleAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(1, 1)];
        [self.textLabel pop_addAnimation:scaleAnimation forKey:@&quot;scalingUp&quot;];
        
        
        
    } else {
        POPSpringAnimation *sprintAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPViewScaleXY];
        sprintAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(0.9, 0.9)];
        sprintAnimation.velocity = [NSValue valueWithCGPoint:CGPointMake(2, 2)];
        sprintAnimation.springBounciness = 20.f;
        [self.textLabel pop_addAnimation:sprintAnimation forKey:@&quot;springAnimation&quot;];
    }
}
</pre>
<p>It is pretty straightforward to use Pop. You first choose a particular type of animation. Like the above example, we pick the POPBasicAnimation when the cell is highlighted and POPSpringAnimation when the user lifts up his/her finger. Once you select the type of animation, the second thing is to provide the animation properties. For both animations, we specify the kPOPViewScaleXY property for scaling the label. Next, we specify toValue which describes your desired end state of the animation. In the above, we set to CGPointMake(1, 1) that scales the object with a value of one. Depending on the type of animation you&#x2019;re creating, you&#x2019;ll have to configure addition settings like springBounciness in spring animations that controls the bouncing effect. Lastly, we add the animation to the text label and give it a name (e.g. springAnimation).</p>
<div class="note">
Note: Pop provides a number of predefined properties for creating animations. You can find out the properties by referring to the POPAnimatableProperty.h.
</div>
<p>Now build and run the app. Highlight any cell and release it to test the animation.</p>
<p><img loading="lazy" decoding="async" width="373" height="664" src="http://www.appcoda.com/wp-content/uploads/2014/12/pop-animation-1-1.gif" alt="Creating Simple Animations with Facebook&apos;s Pop Framework" class="aligncenter size-full wp-image-4498"></p>
<h2>Example #2: Animating a Like Button</h2>
<p>Have you used the Facebook Messenger app? I really like the animation of the Send/Like button when you start to type message to a friend. I decided to use Pop to create a similar animation.</p>
<p>First, create a new view controller in the storyboard. In the view controller, create a text field for comments. Then add a Send and Like buttons. You can download the Like button image here and import it to the image asset. Just place the Like button over the Send button. Later we will write some code to display one of the buttons at a time. By default, the Like button will be displayed. When a user keys in a comment, we will hide the Like button and display the Send button with an animation.</p>
<p><img loading="lazy" decoding="async" width="1024" height="596" src="http://www.appcoda.com/wp-content/uploads/2014/12/facebook-send-ui-design-hd.jpg" alt="Creating Simple Animations with Facebook&apos;s Pop Framework" class="aligncenter size-full wp-image-4505" srcset="https://www.appcoda.com/content/images/wordpress/2014/12/facebook-send-ui-design-hd.jpg 1024w, https://www.appcoda.com/content/images/wordpress/2014/12/facebook-send-ui-design-hd-515x300.jpg 515w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>Lastly, connect the example list view controller with Facebook Like view controller by using a manual segue. Set the identifier of the segue as &#x201C;openFB&#x201D;. Later we&#x2019;ll use code to trigger the segue.</p>
<p>Once you designed the user interface, create a new class called FacebookButtonAnimationViewController and set it as the custom class of the view controller.</p>
<p>Next, create the outlet variables for both Like and Send buttons, as well as, the text field. Your outlet variable should look like this:</p>
<pre lang="objective-c">
@interface FacebookButtonAnimationViewController ()
@property (weak, nonatomic) IBOutlet UIButton *likeButton;
@property (weak, nonatomic) IBOutlet UIButton *sendButton;
@property (weak, nonatomic) IBOutlet UITextField *msgTextField;

@end
</pre>
<p>In FacebookButtonAnimationViewController.h, import POP.h and implement the UITextFieldDelegate:</p>
<pre lang="objective-c">
#import <uikit uikit.h>
#import <pop pop.h>

@interface FacebookButtonAnimationViewController : UIViewController <uitextfielddelegate>

@end
</uitextfielddelegate></pop></uikit></pre>
<p>In the viewDidLoad method of FacebookButtonAnimationViewController.m, insert the following line of code to set the delegate of text field and hide the Send button:</p>
<pre lang="objective-c">
self.msgTextField.delegate = self;
self.sendButton.hidden = YES;
</pre>
<p>Now we will implement the methods for handling the text field. Insert these methods in the same file:</p>
<pre lang="objective-c">
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *comment;
    
    if (range.length == 0) {
        comment = [NSString stringWithFormat:@&quot;%@%@&quot;, textField.text, string];
    } else {
        comment = [textField.text substringToIndex:textField.text.length - range.length];
    }
    
    if (comment.length == 0) {
        // Show Like
        [self showLikeButton];
    } else  {
        // Show Send
        [self showSendButton];
    }
    
    return YES;
}
</pre>
<p>The shouldChangeCharactersInRange method is called every time when whenever the user types a new character or delete a character in the text field. If the text field is empty, we display the Like button. On the other hand, if the text field contains any characters, we display the Send button.</p>
<p>Next, we implement both showLikeButton and showSendButton methods:</p>
<pre lang="objective-c">
- (void)showSendButton {
    if (self.sendButton.isHidden) {
        self.likeButton.hidden = YES;
        self.sendButton.hidden = NO;
        
        POPSpringAnimation *sprintAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPViewScaleXY];
        
        sprintAnimation.velocity = [NSValue valueWithCGPoint:CGPointMake(8, 8)];
        sprintAnimation.springBounciness = 20.f;
        [self.sendButton pop_addAnimation:sprintAnimation forKey:@&quot;sendAnimation&quot;];
    }
}

-(void)showLikeButton {
    self.likeButton.hidden = NO;
    self.sendButton.hidden = YES;
    
    POPSpringAnimation *spin = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerRotation];
    
    spin.fromValue = @(M_PI / 4);
    spin.toValue = @(0);
    spin.springBounciness = 20;
    spin.velocity = @(10);
    [self.likeButton.layer pop_addAnimation:spin forKey:@&quot;likeAnimation&quot;];
}
</pre>
<p>In the showSendButton method, we hide the Like button and show the Send button, and then apply a spring animation with the kPOPViewScaleXY property on the Send button. </p>
<p>The same technique is used for the Like button but we apply a rotation animation instead. We first create an instance of POPSpringAnimation and then set the &#x201C;from&#x201D; and &#x201C;to&#x201D; values.  The Like button is rotated from 45 degrees (i.e. M_PI/4) to 0 degree with bounciness set to 20. </p>
<p>Lastly, insert the following method in ExamplesListViewController.m to trigger the segue:</p>
<pre lang="objective-c">
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
            [self performSegueWithIdentifier:@&quot;openFB&quot; sender:self];
            break;
        case 1:
            [self performSegueWithIdentifier:@&quot;openWrongPass&quot; sender:self];
            break;
        case 2:
            [self performSegueWithIdentifier:@&quot;openCustomTransition&quot; sender:self];
            break;
            
        default:
            break;
    }
}
</pre>
<p>Now it is ready to test the app. Hit the Run button and key in a character in the text field to test the animation.</p>
<p><img loading="lazy" decoding="async" width="374" height="667" src="http://www.appcoda.com/wp-content/uploads/2014/12/pop-animation-2.gif" alt="Creating Simple Animations with Facebook&apos;s Pop Framework" class="aligncenter size-full wp-image-4492"></p>
<h2>Example #3: Wrong Password Animation</h2>
<p>As a Mac user, you should be very familiar with the password field in Mac OS X. When you type a wrong password during login, the text field shakes. In this example, we&#x2019;ll use Pop to replicate the animation.</p>
<p>First, go to Interface Builder and add a new view controller. Then add a text field and a Login button. Again, create a manual segue between the Example List View Controller and the new view controller. Set the segue&#x2019;s identifier to &#x201C;openWrongPass&#x201D;. Your user interface should be similar to this:</p>
<p><img loading="lazy" decoding="async" width="1024" height="596" src="http://www.appcoda.com/wp-content/uploads/2014/12/pop-wrong-password-ui-hd.jpg" alt="Creating Simple Animations with Facebook&apos;s Pop Framework" class="aligncenter size-full wp-image-4509" srcset="https://www.appcoda.com/content/images/wordpress/2014/12/pop-wrong-password-ui-hd.jpg 1024w, https://www.appcoda.com/content/images/wordpress/2014/12/pop-wrong-password-ui-hd-515x300.jpg 515w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>Next, create a new class called WrongPasswordViewController and set it as the custom class of the new view controller. Create an outlet variable for the text field and name it passwordTextField.</p>
<pre lang="objective-c">
@interface WrongPasswordViewController ()
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;

@end
</pre>
<p>Then we create an action method named &#x201C;login&#x201D; for the Login button.</p>
<p>As said before, we will apply a &#x201C;shake&#x201D; animation on the text field to indicate a wrong password. For demo purpose, we will not verify the password. We will just show the animation whenever the user clicks the Login button.</p>
<p>Implement the login method like this:</p>
<pre lang="objective-c">
- (IBAction)login:(id)sender {
    
    POPSpringAnimation *shake = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPositionX];
    
    shake.springBounciness = 20;
    shake.velocity = @(3000);
    
    [self.passwordTextField.layer pop_addAnimation:shake forKey:@&quot;shakePassword&quot;];

}
</pre>
<p>The above code is pretty straightforward. We create the POPSpringAnimation with the kPOPLayerPositionX property. This property simply moves the text field along the X axis.</p>
<p>Lastly, remember to import the POP.h at the beginning of the WrongPasswordViewController.m:</p>
<pre lang="objective-c">
#import <pop pop.h>
</pop></pre>
<p>Cool! Compile and run the app to test the animation.</p>
<p><img loading="lazy" decoding="async" width="373" height="664" src="http://www.appcoda.com/wp-content/uploads/2014/12/pop-animation-3-2.gif" alt="Creating Simple Animations with Facebook&apos;s Pop Framework" class="aligncenter size-full wp-image-4497"></p>
<h2>Example #4: Custom View Controller Transition</h2>
<p>In the last example, I will show you how to present a view controller with a custom animation. We will a view controller with a single button &#x201C;Present&#x201D;. When a user taps the button, the app presents another view controller modally with a custom animation. Since iOS 7, you can customise the view transition by using the transitioningDelegate of UIViewController. The delegate, which should conform to UIViewControllerAnimatedTransitioning, provides the transition animator that animates the transition of view controllers. </p>
<p>First, create two view controllers in the storyboard and two new classes. Name one class &#x201C;CustomVCTransitionViewController&#x201D; and the other &#x201C;CustomModalViewController&#x201D;. Set these classes as the custom class of the controllers. For the modal view controller (in red), set the storyboard ID to &#x201C;customModal&#x201D;. Further, connect the Example List View Controller with the CustomVCTransitionViewController using a manual segue. Set the identifier of the segue to &#x201C;openCustomTransition&#x201D;.</p>
<p>Your UI design should look like this:</p>
<p><img loading="lazy" decoding="async" width="1024" height="596" src="http://www.appcoda.com/wp-content/uploads/2014/12/custom-view-controller-ui-hd.jpg" alt="Creating Simple Animations with Facebook&apos;s Pop Framework" class="aligncenter size-full wp-image-4508" srcset="https://www.appcoda.com/content/images/wordpress/2014/12/custom-view-controller-ui-hd.jpg 1024w, https://www.appcoda.com/content/images/wordpress/2014/12/custom-view-controller-ui-hd-515x300.jpg 515w" sizes="(max-width: 1024px) 100vw, 1024px"></p>
<p>You can have a quick test of the app. When you select Custom VC Transition, the CustomVCTransitionController should appear. </p>
<p>Now we&#x2019;ll implement the CustomVCTransitionViewController to handle the Present button. Insert the following line of code in CustomVCTransitionViewController.h to adopt the UIViewControllerTransitioningDelegate protocol:</p>
<pre lang="objective-c">
@interface CustomVCTransitionViewController : UIViewController <uiviewcontrollertransitioningdelegate>
</uiviewcontrollertransitioningdelegate></pre>
<p>In CustomVCTransitionViewController.m, add the following lines of code to import the header files:</p>
<pre lang="objective-c">
#import &quot;CustomModalViewController.h&quot;
#import &quot;PresentingAnimationController.h&quot;
#import &quot;DismissingAnimationController.h&quot;
#import <pop pop.h>
</pop></pre>
<p>Then insert the following methods to implement the action method of the Present button and the required methods of the protocol:</p>
<pre lang="objective-c">
- (IBAction)didClickOnPresent:(id)sender {
    
    CustomModalViewController *modalVC = [self.storyboard instantiateViewControllerWithIdentifier:@&quot;customModal&quot;];
    
    
    modalVC.transitioningDelegate = self;
    
    modalVC.modalPresentationStyle = UIModalPresentationCustom;
    
    [self.navigationController presentViewController:modalVC animated:YES completion:nil];
}

#pragma mark - UIViewControllerTransitionDelegate -

- (id <uiviewcontrolleranimatedtransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [[PresentingAnimationController alloc] init];
}

- (id <uiviewcontrolleranimatedtransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return [[DismissingAnimationController alloc] init];
}
</uiviewcontrolleranimatedtransitioning></uiviewcontrolleranimatedtransitioning></pre>
<p>When the button is tapped, the didClickOnPresent method will be invoked. Here we instantiate the modal view controller and set the transitioning delegate to the current view controller. We also set the modal presentation style to custom. (With the action method, remember to establish a connection between the Present button and the method in storyboard.)</p>
<p>As the class adopts the UIViewControllerTransitioningDelegate protocol, we implement the two required methods.  The animationControllerForPresentedController: method returns the transition animator object to use when presenting the modal view controller. Conversely, the animationControllerForDismissedController: method provides the animator object for dismissing a view controller. </p>
<p>We haven&#x2019;t created both animator classes yet. Now create a new class called PresentingAnimationController, set it as a subclass of NSObject and adopt the UIViewControllerAnimatedTransitioning protocol:</p>
<pre lang="objective-c">
#import <uikit uikit.h>
#import &quot;POP.h&quot;

@interface PresentingAnimationController : NSObject <uiviewcontrolleranimatedtransitioning>
</uiviewcontrolleranimatedtransitioning></uikit></pre>
<p>In PresentingAnimationController.m, add the following methods:</p>
<pre lang="objective-c">
- (NSTimeInterval)transitionDuration:(id <uiviewcontrollercontexttransitioning>)transitionContext {
    return 0.5f;
}

- (void)animateTransition:(id <uiviewcontrollercontexttransitioning>)transitionContext {
    
    UIView *fromView = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey].view;
    fromView.tintAdjustmentMode = UIViewTintAdjustmentModeDimmed;
    fromView.userInteractionEnabled = NO;
    
    UIView *toView = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey].view;
    toView.frame = CGRectMake(0,
                              0,
                              CGRectGetWidth(transitionContext.containerView.bounds) - 100.f,
                              CGRectGetHeight(transitionContext.containerView.bounds) - 280.f);
    CGPoint p = CGPointMake(transitionContext.containerView.center.x, -transitionContext.containerView.center.y);
    toView.center = p;
    
    [transitionContext.containerView addSubview:toView];
    
    POPSpringAnimation *positionAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPositionY];
    positionAnimation.toValue = @(transitionContext.containerView.center.y);
    positionAnimation.springBounciness = 10;
    [positionAnimation setCompletionBlock:^(POPAnimation *anim, BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
    
    POPSpringAnimation *scaleAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerScaleXY];
    scaleAnimation.springBounciness = 20;
    scaleAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(1.2, 1.4)];
    
    [toView.layer pop_addAnimation:positionAnimation forKey:@&quot;positionAnimation&quot;];
    [toView.layer pop_addAnimation:scaleAnimation forKey:@&quot;scaleAnimation&quot;];
    
}
</uiviewcontrollercontexttransitioning></uiviewcontrollercontexttransitioning></pre>
<p>The first method defines the transition duration (i.e. 0.5 seconds). To animate the transition, we implement the animateTransition: method. Here we define how the transition animations are performed. We first retrieve the &#x201C;fromView&#x201D; involved in the transition using the viewControllerForKey: method of the transitionContext. Next, we retrieve the &#x201C;toView&#x201D;. Once you have these two views, you can apply any animations during the view transition. Here we apply two animations &#x2013; position animation and scale animation. The position animation slides the view from the top of the screen to the center. The scale animation scales up the view a bit and then scales it back to the normal values.</p>
<p>Next, create a new class named DismissingAnimationController and adopt the UIViewControllerAnimatedTransitioning protocol:</p>
<pre lang="objective-c">
#import <foundation foundation.h>
#import <uikit uikit.h>
#import <pop pop.h>

@interface DismissingAnimationController : NSObject <uiviewcontrolleranimatedtransitioning>

@end
</uiviewcontrolleranimatedtransitioning></pop></uikit></foundation></pre>
<p>Similarly, we create the dismissing animation by implementing the required method of the UIViewControllerAnimatedTransitioning protocol:</p>
<pre lang="objective-c">
- (NSTimeInterval)transitionDuration:(id <uiviewcontrollercontexttransitioning>)transitionContext {
    return 0.5f;
}

- (void)animateTransition:(id <uiviewcontrollercontexttransitioning>)transitionContext {
    
    UIView *toView = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey].view;
    toView.tintAdjustmentMode = UIViewTintAdjustmentModeNormal;
    toView.userInteractionEnabled = YES;
    
    UIView *fromView = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey].view;
    
    
    POPBasicAnimation *closeAnimation = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerPositionY];
    closeAnimation.toValue = @(-fromView.layer.position.y);
    [closeAnimation setCompletionBlock:^(POPAnimation *anim, BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
    
    POPSpringAnimation *scaleDownAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerScaleXY];
    scaleDownAnimation.springBounciness = 20;
    scaleDownAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)];
    
    [fromView.layer pop_addAnimation:closeAnimation forKey:@&quot;closeAnimation&quot;];
    [fromView.layer pop_addAnimation:scaleDownAnimation forKey:@&quot;scaleDown&quot;];
    
}
</uiviewcontrollercontexttransitioning></uiviewcontrollercontexttransitioning></pre>
<p>When dismissing the modal view, we apply two animations &#x2013; close animation and scale down animation. By combining both animations, we make the modal view disappear or move off screen.</p>
<p>Go back to the CustomModalViewController.m, update the viewDidLoad method and implement the didClickOnClose method:</p>
<pre lang="objective-c">
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Round corner
    self.view.layer.cornerRadius = 8.f; 
}

- (IBAction)didClickOnClose:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
</pre>
<p>Finally, establish a connection between the Close button with the didClickOnClose method in InterfaceBuilder.</p>
<p>Cool! It&#x2019;s ready to test the app. Run it and test the view transition.</p>
<p><img loading="lazy" decoding="async" width="373" height="664" src="http://www.appcoda.com/wp-content/uploads/2014/12/pop-animation-4.gif" alt="Creating Simple Animations with Facebook&apos;s Pop Framework" class="aligncenter size-full wp-image-4500"></p>
<h2>Summary</h2>
<p>In this tutorial, I gave you an introduction of Facebook&#x2019;s Pop framework. As you can see, the animation engine is pretty easy to use. If you understand the animation techniques covered in the tutorial, you should be able to create your own animation in your apps.</p>
<p>For your reference, you can download the complete Xcode project <a href="https://www.dropbox.com/s/myrvq3dhuevjn8k/POPDemo.zip?dl=0&amp;ref=appcoda.com">here</a>. Or you can check out <a href="https://github.com/most-wanted/Facebook-POP-Tutorial?ref=appcoda.com">the project on Github</a>.</p>
<p>What do you think about the tutorial? Leave me comment and share your thought.</p>

<!--kg-card-end: html-->
]]></content:encoded></item><item><title><![CDATA[Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>Hello readers! iOS 8 is at the gates, as only a few weeks remain until the official release of the updated version of the operating system, and along with it, the release of the <a href="http://www.appcoda.com/swift-programming-language-intro/">Swift programming language</a>. So, as you understand, we are preparing to enter into a new era</p>]]></description><link>https://www.appcoda.com/ios-gesture-recognizers/</link><guid isPermaLink="false">66612a0f166d3c03cf011380</guid><category><![CDATA[iOS Programming]]></category><category><![CDATA[Objective C]]></category><dc:creator><![CDATA[Gabriel Theodoropoulos]]></dc:creator><pubDate>Mon, 25 Aug 2014 21:13:54 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2014/08/gestures-featured.jpg" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://www.appcoda.com/content/images/wordpress/2014/08/gestures-featured.jpg" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures"><p>Hello readers! iOS 8 is at the gates, as only a few weeks remain until the official release of the updated version of the operating system, and along with it, the release of the <a href="http://www.appcoda.com/swift-programming-language-intro/">Swift programming language</a>. So, as you understand, we are preparing to enter into a new era of the iOS SDK, where new wonderful technologies waiting for us to explore them! However, here at Appcoda we decided to dedicate one more tutorial to the existing SDK, using the Objective-C language. My next tutorials will focus on new iOS 8 technologies, and we&#x2019;ll use the Swift language. Regarding this one, there were many candidate topics to write for, but ultimately the chosen one is about the <strong>Gesture Recognizers</strong>. So, let&#x2019;s see a few things about them.</p>
<p>A <em>gesture recognizer</em> is actually an object of the abstract class <em><a href="https://developer.apple.com/library/ios/documentation/uikit/reference/UIGestureRecognizer_Class/Reference/Reference.html?ref=appcoda.com">UIGestureRecognizer</a></em>. Such an object is related to a view, and monitors for predefined gestures made on that view. Going one level deeper, I would say that gestures are actually <em>touches</em> and <em>movements</em> of one or more fingers that happen on a specific area of the screen, where a view of interest exists there. In the early versions of iOS SDK, gestures recognizers were not provided to developers, so implementing such ways of interaction required a lot of manual work. Thankfully, Apple wrapped up all that manual work and gave it to developers as a single tool, and that way working with gestures became a really easy part of the iOS programming.</p>
<p>The <em>UIGestureRecognizer</em> class as an abstract one, it can&#x2019;t be used directly. There are specific subclasses of it that are provided for usage, and each one of them deals with a specific kind of gesture. Let&#x2019;s go through them for a while and let&#x2019;s see what the respective gestures are for:</p>
<ol>
<li><em>UITapGestureRecognizer</em>: This class regards the <em>tap</em> gestures made on a view. It can be used to handle single or multiple taps, either with one or more fingers. Tapping is one of the most usual gestures that users make.</li>
<li><em>UISwipeGestureRecognizer</em>: Another important gesture is the <em>swipe</em>, and this class exists just for it. Swiping happens when dragging a finger towards a direction (right, left, top and down). A characteristic example of the swipe gesture exists on the Photos app, where we use our fingers to slide from one photo to another.</li>
<li><em>UIPanGestureRecognizer</em>: The <em>pan</em> gesture is actually a <em>drag</em> gesture. It&#x2019;s used when it&#x2019;s needed to drag views from one point to another.</li>
<li><em>UIPinchGestureRecognizer</em>: When you view photos on the Photos app and you use your two fingers to zoom in or out to a photo, then you perform a <em>pinch</em> gesture. As you understand, pinching requires two fingers. An object of this class is usually handy to change the transform of a view, and more specifically its scale. Using pinch gestures for example, you can implement zoom in and out to photos on your own apps.</li>
<li><em>UIRotationGestureRecognizer</em>: In accordance to the previous gesture, <em>rotation</em> is used to rotate a view using two fingers.</li>
<li><em>UILongPressGestureRecognizer</em>: An object of that class monitors for long press gestures happening on a view. The pressing must last long enough in order to be detected, and the finger or fingers should not move a lot around the pressed point otherwise the gesture fails.</li>
<li><em>UIScreenEdgePanGestureRecognizer</em>: This one is similar to the swipe gesture, but with a great difference: The finger movement should always begin from an edge of the screen.</li>
</ol>
<p>All gesture objects perform an <em>action</em> once a valid gesture is detected. This is either an <em>IBAction</em> method in case the gesture is added through Interface Builder, or a private or public method in case of programmatic implementation. When an action method is called after a gesture has happened, the gesture object always sends itself in case additional info is required when handling the gesture. It&#x2019;s not necessary to declare the action methods in order to contain the gesture object to their signatures, but personally I recommend you to do so as a better programming practice. For example, both of the following method signatures are valid:</p>
<pre lang="objc">-(void)handleMyTapGesture;
-(void)handleMyTapGestureWithGestureRecognizer:(UITapGestureRecognizer *)gestureRecognizer;
</pre>
<p>In the second case, the <em>gestureRecognizer</em> argument can provide you with extra info you might need, such as the view that the gesture took place on. In my examples in this tutorial, I&#x2019;ll use the second method signature when declaring methods for handling gestures.</p>
<p>Looking now from the point of views, a view can contain more than one gesture recognizers. For instance, you can add both pinch and rotation gesture recognizers to an <em>imageview</em>, so you can zoom in/out and rotate the presented image. However, just one gesture at a given time can occur. Gesture recognizers that are related to a view are added to an array of that view, so you can access them as you would do for any object to a normal array. I guess though that you will rarely need to access a gesture recogniser object in such way.</p>
<p>As you will see next to this tutorial, working with gesture recognizers is easy enough, and it consists of a pretty awesome way to provide interaction to your app without using the traditional subviews for performing actions (such as buttons). Before we continue, I should mention that we are going to focus our attention to the first five gesture recognizer classes, while for the last two we&#x2019;ll just say a couple of words about each one of them. That&#x2019;s because they have great similarities to other classes, so it would be pointless to discuss about the same stuff twice. Furthermore, I said previously that the gesture recognizers can be added in two ways to views: Either using the Interface Builder, or programmatically. In here I am going to follow the second path, and do everything in code. If you want to read more theoretical stuff about gesture recognizers, then feel free to pay a visit to the official documentation provided by Apple.</p>
<h2>Demo App Overview</h2>
<p>The way that we are going to work in this tutorial is straightforward enough. First of all, we will create a <em>tabbed</em> application, which will contain five tabs. Each tab will match to a single view controller, and each view controller will be used to demonstrate a new gesture recognizer. Furthermore, we will create five view controller classes to implement the necessary code for every gesture recognizer that we will meet.</p>
<p>The gesture recognizers that we are going to work with are in the following order:</p>
<ol>
<li>Tap gesture recognizer</li>
<li>Swipe gesture recognizer</li>
<li>Pan gesture recognizer</li>
<li>Pinch gesture recognizer</li>
<li>Rotation gesture recognizer</li>
</ol>
<p>For each one of them, we are going to create one or more test views, and then we will implement the necessary code that will make the respective gestures properly work. So, I could say that the demo application of this tutorial will be parted by many small examples, where each one of them targets for the study of a single gesture recognizer.</p>
<h2>App Creation and Setup</h2>
<p>Let&#x2019;s begin by creating a new project in Xcode. Launch it, and in the first step of the guide select the <strong>Tabbed Application</strong> as the template for your project.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_1_new_project1.jpg" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3985" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_1_new_project1.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_1_new_project1-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Next, set the <strong>GesturesDemo</strong> as the name of the project, and make sure that the <strong>iPhone</strong> is the selected device.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_2_new_project2.jpg" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3986" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_2_new_project2.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_2_new_project2-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Get finished with the guide by selecting a directory to store the project, and you are ready.</p>
<p>Now that the project has been prepared, let&#x2019;s setup our interface so we can start working with the gesture recognizers at once later. Click on the <em>Main.storyboard</em> file, and let the Interface Builder appear. As you notice, there are two view controllers connected to the tab bar controller already, so we need to add three more. From the Object Library, drag and drop three new View Controller objects to the IB canvas.</p>
<p>Before we connect the view controllers to the tab bar, we must create the necessary view controller classes. Begin by selecting the <em>FirstViewController</em> and <em>SecondViewController</em> classes (both the .h and .m files) on the Project Navigator, and then hit the Delete key on your keyboard. We are not going to use these files, we will create new classes for the gesture recognizers that we&#x2019;ll work with.</p>
<p><img loading="lazy" decoding="async" width="260" height="330" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_3_selected_files.png" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3987" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_3_selected_files.png 260w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_3_selected_files-236x300.png 236w" sizes="(max-width: 260px) 100vw, 260px"></p>
<p>In the confirmation dialog box that shows up, click on the <em>Move to Trash</em> button.</p>
<p><img loading="lazy" decoding="async" width="552" height="153" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_4_move_to_trash.png" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3988"></p>
<p>Next, start adding the new classes to the project. The procedure that will be presented right next should be repeated five times in total, until all the necessary classes to have been added to the project. Let&#x2019;s see everything in details for the first one:</p>
<p>Open the <strong>File &gt; New &gt; File&#x2026;</strong> menu, and select to create a new <strong>Objective-C</strong> class in the guide that appears.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_5_new_file1.jpg" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3989" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_5_new_file1.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_5_new_file1-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Move to the next step, and in the <strong>Subclass of</strong> field, make sure that the set value is the <strong>UIViewController</strong> one. If not, then do it now. Next, name the new class by setting the <strong>TapViewController</strong> value in the <strong>Class</strong> field.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_6_new_file2.jpg" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3990" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_6_new_file2.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_6_new_file2-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Proceed and in the last step click on the Create button to get finished with the guide and let Xcode create and add the new class to the project.</p>
<p>For the next view controllers that you will create, set the following class names:</p>
<ul>
<li><strong>SwipeViewController</strong></li>
<li><strong>PanViewController</strong></li>
<li><strong>PinchViewController</strong></li>
<li><strong>RotationViewController</strong></li>
</ul>
<p>After you have added all of them, here&#x2019;s how your Project Navigator should look like:</p>
<p><img loading="lazy" decoding="async" width="260" height="424" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_7_new_classes.png" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3991"></p>
<p>Now we can return to Interface Builder. Firstly, make sure that the Utilities pane is on, because you will need it. Next, select the first view controller scene (let&#x2019;s start from top to bottom), and show the <strong>Identity Inspector</strong> in the Utilities pane. In there, in the <strong>Class</strong> field of the <strong>Custom Class</strong> section, set the name of the first class you added to the project, the *<em>TapViewController</em>:</p>
<p><img loading="lazy" decoding="async" width="600" height="328" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_8_set_custom_class.png" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3992" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_8_set_custom_class.png 600w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_8_set_custom_class-548x300.png 548w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Repeat the above step until you set all the custom classes to the remaining view controllers.</p>
<p>Our next move is to connect all the view controllers to the tab bar controller. This is can be done very easily, if you select the tab bar controller and then you open the <strong>Connections Inspector</strong> to the Utilities pane. In the <strong>Triggered Segues</strong> section, click on the circle on the right of the <strong>view controllers</strong> option and drag on top of every not connected view controller, and proceed by connecting them one by one.</p>
<p><img loading="lazy" decoding="async" width="600" height="357" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_9_connect_viewcontrollers.png" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3993" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_9_connect_viewcontrollers.png 600w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_9_connect_viewcontrollers-504x300.png 504w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Once all the connections have been made, you can set the titles of the bar button items of the view controllers. Starting from the top to bottom once again, select the tab bar item and then open the <strong>Attributes Inspector</strong> in the Utilities pane. In there, set the proper tab bar title for each view controller, and set the <em>first</em> as the image to all view controllers.</p>
<p><img loading="lazy" decoding="async" width="600" height="412" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_10_set_tabbaritem.png" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3994" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_10_set_tabbaritem.png 600w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_10_set_tabbaritem-436x300.png 436w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>The tab bar item titles are in order:</p>
<ul>
<li>Tap</li>
<li>Swipe</li>
<li>Pan</li>
<li>Pinch</li>
<li>Rotation</li>
</ul>
<p>Finally, remove the existing content from the first two pre-made view controllers.</p>
<p>Everything is ready now. Optionally, you can add a label as a title to each view controller. If you would like to do that too, then drag a <em>UILabel</em> object to each view controller and set the following attributes:</p>
<ul>
<li><strong>Frame</strong>: X=20, Y=40, Width=280, Height=40</li>
<li><strong>Font</strong>: System Bold, 20pt</li>
<li><strong>Alignment</strong>: Center</li>
</ul>
<p>The texts of the labels should be (following the same order as before):</p>
<ul>
<li>Tap Gesture</li>
<li>Swipe Gesture</li>
<li>Pan Gesture</li>
<li>Pinch Gesture</li>
<li>Rotation Gesture</li>
</ul>
<p>Now that we have setup the base that we&#x2019;ll work on, we can dive directly in the heart of our topic. However, we&#x2019;ll return several times here in Interface Builder with an aim to create the needed test views for each gesture recognizer.</p>
<p><img loading="lazy" decoding="async" width="236" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_11_view_controllers_complete.png" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3995" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_11_view_controllers_complete.png 236w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_11_view_controllers_complete-157x300.png 157w" sizes="(max-width: 236px) 100vw, 236px"></p>
<h2>Tap Gesture Recognizer</h2>
<p>We begin the real exploration of our today&#x2019;s topic with the tap gesture recognizer, as you assume from the title of this section. In the previous part, you added all the needed view controllers to the project and you connected them with the tab bar controller. Now in this part, we are going to add a view object (<em>UIView</em>) to the <em>Tap view controller scene</em>, which we will use as a test view in order to do our work in code.</p>
<p>At first, make sure that you have the Interface Builder still on by clicking on the <em>Main.storyboard</em> file in the Project Navigator. Next, bring the <em>Tap view controller scene</em> right in front of you, and then grab an <em>UIView</em> object from the Object Library and drag it to the scene&#x2019;s view. Set the following properties to that view:</p>
<ul>
<li><strong>Frame</strong>: X=110, Y=234, Width=100, Height=100</li>
<li><strong>Background Color</strong>: R=215, G=116, B=52 (or any other color you like)</li>
</ul>
<p><img loading="lazy" decoding="async" width="383" height="464" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_12_tap_gesture_testview.png" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3996" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_12_tap_gesture_testview.png 383w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_12_tap_gesture_testview-247x300.png 247w" sizes="(max-width: 383px) 100vw, 383px"></p>
<p>Now that the view is in place, we must create an IBOutlet property and connect it with the view. Open the <em>TapViewController.h</em> file and declare the following property:</p>
<pre lang="objc">@interface TapViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *testView;

@end
</pre>
<p>Back on the <em>Main.storyboard</em> file again, go to the Document Outline pane, and Ctrl-Drag from the <em>Tap view controller scene</em> object to the view, as shown below:</p>
<p><img loading="lazy" decoding="async" width="273" height="357" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_13_connect_iboutlet_property.png" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3997" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_13_connect_iboutlet_property.png 273w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_13_connect_iboutlet_property-229x300.png 229w" sizes="(max-width: 273px) 100vw, 273px"></p>
<p>In the black popup window, just select the <em>testView</em> property, and you are all set.</p>
<p><img loading="lazy" decoding="async" width="270" height="324" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_14_select_iboutlet_property.png" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3998" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_14_select_iboutlet_property.png 270w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_14_select_iboutlet_property-250x300.png 250w" sizes="(max-width: 270px) 100vw, 270px"></p>
<p><em>Note: We are going to use the above procedure for adding test view objects and for connecting them with IBOutlet properties to the upcoming chapters as well. However, I&#x2019;m not going to get into much detail again, so if you need you may return back here to follow the steps that were just described.</em></p>
<p>Now, open the <em>TapViewController.m</em> file. The first thing we must do, is to create an object of the <em>UITapGestureRecognizer</em> class, which we&#x2019;ll then add to the <em>testView</em> view. Actually, we will create two objects of that class, one for testing single taps, and one for testing double taps. Our work will take place initially to the <em>viewDidLoad</em> method, so let&#x2019;s get started with the first one.</p>
<p>The next code segment clearly displays how we initialize a gesture recognizer object:</p>
<pre lang="objc">UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapGesture:)];
</pre>
<p>Using that way, you can initialize any object of the gesture recognizer subclasses, as long as you replace the name of the class. As you see, we specify a <em>target</em> and an <em>action</em>. The action in this case is a private method that we are about to create in a few seconds.</p>
<p>To assign the above gesture recognizer to our test view, here&#x2019;s what we should write:</p>
<pre lang="objc">[self.testView addGestureRecognizer:singleTapGestureRecognizer];
</pre>
<p>The <em>addGestureRecognizer:</em> method is the one and standard way of adding a gesture recognizer object to a view.</p>
<p>Go now to the private section of the interface, and declare the private method we set to the gesture recognizer as follows:</p>
<pre lang="objc">@interface TapViewController ()

-(void)handleSingleTapGesture:(UITapGestureRecognizer *)tapGestureRecognizer;

@end
</pre>
<p>As I said in the introduction, the gesture recognizer object passes itself to the selector method, and by using this method signature we can use it later in the implementation. We could omit the parameter, but that&#x2019;s something that I am intentionally going to avoid to the whole tutorial.</p>
<p>Let&#x2019;s move forward to the method&#x2019;s definition now. What are we going to do there? Well, nothing hard especially. We will just double the width of the test view when we tap on it once, and we will revert the original width value upon the second tap (an so on). Let&#x2019;s see it:</p>
<pre lang="objc">-(void)handleSingleTapGesture:(UITapGestureRecognizer *)tapGestureRecognizer{
    CGFloat newWidth = 100.0;
    if (self.testView.frame.size.width == 100.0) {
        newWidth = 200.0;
    }

    CGPoint currentCenter = self.testView.center;

    self.testView.frame = CGRectMake(self.testView.frame.origin.x, self.testView.frame.origin.y, newWidth, self.testView.frame.size.height);
    self.testView.center = currentCenter;
}
</pre>
<p>The implementation is really simple. At first we check if the initial width of the view is equal to 100.0 points, and if so we make it 200.0, otherwise we keep the initial assigned value (100.0). Next, we keep to a CGPoint structure variable the current center point, we change the width of the view and we center it again.</p>
<p>It&#x2019;s now time to try out the tap gesture. Run the app, and once it gets launched to either the Simulator or a device, make sure that you are on the first tab. Tap on the view once, and its size will change. Tap once again, and watch it going back to its original state. Simple and cool?</p>
<p><img loading="lazy" decoding="async" width="320" height="588" src="http://www.appcoda.com/wp-content/uploads/2014/08/tap_gesture_demo.gif" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-4001"></p>
<p>Let&#x2019;s go back to our work again. As I have already said, a tap gesture can be performed with one or more fingers, and the gesture could require one or more taps. So, let&#x2019;s see one more example, where this time we will &#x201C;tell&#x201D; to the gesture recognizer object that we want two taps to happen, and that two fingers are required in order to perform the predefined action. In the <em>viewDidLoad</em> method, add the next lines:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    UITapGestureRecognizer *doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTapGesture:)];
    doubleTapGestureRecognizer.numberOfTapsRequired = 2;
    doubleTapGestureRecognizer.numberOfTouchesRequired = 2;
    [self.testView addGestureRecognizer:doubleTapGestureRecognizer];
}
</pre>
<p>Here we initialize a new tap gesture recognizer object, and we specify another action method that we&#x2019;ll implement in a while. The new thing here though is the use of the two properties that allow us to set the number of the required taps and touches (or in other words, the number of fingers). Finally, we add the recognizer object to the <em>testView</em> view.</p>
<p>Note that our test view now contains two gesture recognizer objects.</p>
<p>Now, let&#x2019;s get finished with the remaining tasks. Go to the private interface section and declare the new private method:</p>
<pre lang="objc">@interface TapViewController ()

...

-(void)handleDoubleTapGesture:(UITapGestureRecognizer *)tapGestureRecognizer;

@end
</pre>
<p>In its definition, we will change both the width and height of the view by doubling its size. We will follow the same logic as before:</p>
<pre lang="objc">-(void)handleDoubleTapGesture:(UITapGestureRecognizer *)tapGestureRecognizer{
    CGSize newSize = CGSizeMake(100.0, 100.0);
    if (self.testView.frame.size.width == 100.0) {
        newSize.width = 200.0;
        newSize.height = 200.0;
    }

    CGPoint currentCenter = self.testView.center;

    self.testView.frame = CGRectMake(self.testView.frame.origin.x, self.testView.frame.origin.y, newSize.width, newSize.height);
    self.testView.center = currentCenter;
}
</pre>
<p>Run the app once again. This time, double-tap and use two fingers, otherwise the gesture will fail. Also, try both of the gesture recognizers we created here:</p>
<p><img loading="lazy" decoding="async" width="320" height="588" src="http://www.appcoda.com/wp-content/uploads/2014/08/double_tap_gesture_demo.gif" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3979"></p>
<p>What you have seen in this part of the tutorial, is more or less the way you work with all the gesture recognizers, even though each one of them has something special about it. For now, we have successfully managed to implement and use tap gestures, and that&#x2019;s quite important!</p>
<h2>Swipe Gesture Recognizer</h2>
<p>Another quite common and cool gesture recognizer is the swipe. Swiping can be done towards any of the four basic directions (right, left, top, bottom) but not in a diagonal way. The <em>UISwipeGestureRecongnizer</em> class provides a method that allows us to specify the direction, and if none is set, then the right direction is used by default. A swipe gesture recognizer object can monitor and trigger actions for one direction only. That means that if you want a view in your application to support swiping towards two or more directions, then you must create two or more gesture recognizer objects respectively. Beyond all that, note that the action that&#x2019;s been triggered by the swipe movement starts right after the swiping is over (when the finger actually stops sliding).</p>
<p>In this part we are going to work with the <em>SwipeViewController</em> class that we previously added to the project. In the respective scene in the Interface Builder, we are going to add three view (<em>UIView</em>) objects. The width of all three views will be equal to the screen&#x2019;s width. The first view will be placed on-screen, while the other two views will be placed at the left and the right side of the first view, and obviously will be out of the visible area. Our goal is to make these views move horizontally using swipe gestures, and to let the hidden views to be revealed by sliding either left or right.</p>
<p>Let&#x2019;s see everything step by step, and let&#x2019;s start by opening the <em>Main.storyboard</em> file. Go to the <em>Swipe view controller scene</em> and add the next three view objects by defining at the same time the frame and background color properties:</p>
<h3>First View</h3>
<ul>
<li><strong>Frame</strong>: X=0, Y=234, Width=320, Height=100</li>
<li><strong>Background Color</strong>: R=215, G=116, B=52</li>
</ul>
<h3>Second View</h3>
<ul>
<li><strong>Frame</strong>: X=320, Y=234, Width=320, Height=100</li>
<li><strong>Background Color</strong>: Black Color</li>
</ul>
<h3>Third View</h3>
<ul>
<li><strong>Frame</strong>: X=-320, Y=234, Width=320, Height=100</li>
<li><strong>Background Color</strong>: R=0, G=128, B=0</li>
</ul>
<p><img loading="lazy" decoding="async" width="378" height="439" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_15_swipe_gesture_testview.png" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3999" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_15_swipe_gesture_testview.png 378w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_15_swipe_gesture_testview-258x300.png 258w" sizes="(max-width: 378px) 100vw, 378px"></p>
<p>Next, create the following IBOutlet properties to the <em>SwipeViewController.h</em> file:</p>
<pre lang="objc">@interface SwipeViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *viewOrange;

@property (weak, nonatomic) IBOutlet UIView *viewBlack;

@property (weak, nonatomic) IBOutlet UIView *viewGreen;

@end
</pre>
<p>After having done so, go back to the <em>Swipe view controller scene</em>, and make the proper connections. Obviously, the <em>viewOrange</em> property matches to the first view, the <em>viewBlack</em> property matches to the second view, and the <em>viewGreen</em> property matches to the third view.</p>
<p>Now, let&#x2019;s head to the <em>SwipeViewController.m</em> file, and let&#x2019;s start creating the gesture recognizers we need one by one. Go to the <em>viewDidLoad</em> method, and initialize such an object for the first view (the one in the middle being in the visible area of the screen). Let&#x2019;s see that:</p>
<pre lang="objc">- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UISwipeGestureRecognizer *swipeRightOrange = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(slideToRightWithGestureRecognizer:)];
    swipeRightOrange.direction = UISwipeGestureRecognizerDirectionRight;

}
</pre>
<p>What we have done with this segment is quite clear: Upon the object initialization we specify the action method that should be called when the swiping will occur, and then we set the direction of the swipe gesture towards right.</p>
<p>Now, let&#x2019;s create one more gesture recognizer object that will enable us to swipe towards left:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    UISwipeGestureRecognizer *swipeLeftOrange = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(slideToLeftWithGestureRecognizer:)];
    swipeLeftOrange.direction = UISwipeGestureRecognizerDirectionLeft;
}
</pre>
<p>Easy, right? What we have only left to do, is to add both of these gesture recognizers to the <em>viewOrange</em> view exactly as shown below:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    [self.viewOrange addGestureRecognizer:swipeRightOrange];
    [self.viewOrange addGestureRecognizer:swipeLeftOrange];
}
</pre>
<p>The action methods we set to the recognizers above, should perform one simple thing: To slide all views either towards left or towards right, so when a view leaves the visible area of the screen, another one to be appeared. Let&#x2019;s declare them first and we&#x2019;ll do the implementation next. In the private interface section add the next lines:</p>
<pre lang="objc">@interface SwipeViewController ()

-(void)slideToRightWithGestureRecognizer:(UISwipeGestureRecognizer *)gestureRecognizer;

-(void)slideToLeftWithGestureRecognizer:(UISwipeGestureRecognizer *)gestureRecognizer;

@end
</pre>
<p>Let&#x2019;s see the implementation of the first method straight away:</p>
<pre lang="objc">-(void)slideToRightWithGestureRecognizer:(UISwipeGestureRecognizer *)gestureRecognizer{
    [UIView animateWithDuration:0.5 animations:^{
        self.viewOrange.frame = CGRectOffset(self.viewOrange.frame, 320.0, 0.0);
        self.viewBlack.frame = CGRectOffset(self.viewBlack.frame, 320.0, 0.0);
        self.viewGreen.frame = CGRectOffset(self.viewGreen.frame, 320.0, 0.0);
    }];
}
</pre>
<p>As you notice, when we swipe towards right, we want the X origin point of each view to be increased by 320.0 pixels and manage that way to move our views to the right. We make this movement look natural simply by wrapping everything into an animation block. Notice also that the movement speed depends on the animation duration, so if you want a slower the slide effect you should increase the animation duration, while if you need them to move faster, then just decrease the duration.</p>
<p>The second action method is going to be similar to this one, with one difference only: The offset on the X axis will be a negative number (equal of course to 320.0 pixels), so the views move to the left. Let&#x2019;s see this implementation as well:</p>
<pre lang="objc">-(void)slideToLeftWithGestureRecognizer:(UISwipeGestureRecognizer *)gestureRecognizer{
    [UIView animateWithDuration:0.5 animations:^{
        self.viewOrange.frame = CGRectOffset(self.viewOrange.frame, -320.0, 0.0);
        self.viewBlack.frame = CGRectOffset(self.viewBlack.frame, -320.0, 0.0);
        self.viewGreen.frame = CGRectOffset(self.viewGreen.frame, -320.0, 0.0);
    }];
}
</pre>
<p>Run the app once again, and this time show the contents of the second tab. Swipe towards right or left, and watch the views slide in and out using an animated fashion. However, when a new view appears on-screen, you&#x2019;ll notice that no swipe gesture works any more. Why that happens?</p>
<p>The answer is simple and lies in the fact that we haven&#x2019;t created and added swipe gesture recognizers to the other two views. So, why don&#x2019;t we do that now, and then see if it works?</p>
<p>Go back to the <em>viewDidLoad</em> method, and start by adding the next segment:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...    

    UISwipeGestureRecognizer *swipeRightBlack = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(slideToRightWithGestureRecognizer:)];
    swipeRightBlack.direction = UISwipeGestureRecognizerDirectionRight;
    [self.viewBlack addGestureRecognizer:swipeRightBlack];
}
</pre>
<p>With these commands, we created a new swipe gesture recognizer for a gesture towards right for the black coloured view, and we used the already implemented <em> slideToRightWithGestureRecognizer :</em> as the action method.</p>
<p>Let&#x2019;s do the same for the green coloured view, but this time we must set the left direction:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    UISwipeGestureRecognizer *swipeLeftGreen = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(slideToLeftWithGestureRecognizer:)];
    swipeLeftGreen.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.viewGreen addGestureRecognizer:swipeLeftGreen];
}
</pre>
<p>Okay, let&#x2019;s give it another try. This time, everything works great!</p>
<p><img loading="lazy" decoding="async" width="320" height="588" src="http://www.appcoda.com/wp-content/uploads/2014/08/swipe_gesture_demo.gif" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3984"></p>
<p>Keep in mind that for every swipe gesture you want to support, you must create a new gesture recognizer object. Creating just one object and adding it to more than one view isn&#x2019;t going to work. If you really want a proof of that, simply go to the <em>viewDidLoad</em> method and add the <em>swipeRightOrange</em> and the <em>swipeLeftOrange</em> gesture recognizers to the other two views respectively. Run the app again, and then swipe your finger (or using the mouse on Simulator) just like before. Unfortunately, this time nothing will work, so set everything back to its original state.</p>
<h2>Pan Gesture Recognizer</h2>
<p>In the last two sections we saw two important gesture recognizers that can give great interaction to your apps. We will continue here by studying another gesture recognizer, the <em>pan</em> or in other words <em>drag</em>. This gesture is handy when you want to allow your users to drag views around the screen. In this part, except for implementing the necessary code that will enable our app to support the pan gesture, we will meet a special method of the <em>UIPanGestureRecognizer</em> class, named <em>velocityInView:</em>. This method returns a CGPoint value, and informs us about how many points per second the dragged view travels in both the horizontal and vertical axis while dragging. This information could be useful in some cases, so we will see how to access it.</p>
<p>Just like before, we&#x2019;ll start by adding a test view to the Interface Builder. Go to the <em>Main.storyboard</em> file, and then drag a view (UIView) object to the <em>Pan view controller scene</em>. Set the next two attributes of it:</p>
<ul>
<li><strong>Frame</strong>: X=110, Y=234, Width=100, Height=100</li>
<li><strong>Background Color</strong>: R=215, G=116, B=52 (or any other color you like)</li>
</ul>
<p>Next, go to the <em>PanViewController.h</em> file and declare an IBOutlet property that you&#x2019;ll later connect to that view:</p>
<pre lang="objc">@interface PanViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *testView;

@end
</pre>
<p>Return to the <em>Main.storyboard</em> file, and connect the IBOutlet property to the view.</p>
<p>Once you have finished working with the Interface Builder, click on the <em>PanViewController.m</em> file in the Project Navigator. The first step we should do, is to create a pan gesture recognizer and add it to our test view. There&#x2019;s nothing difficult in this case, so let&#x2019;s see it:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveViewWithGestureRecognizer:)];
    [self.testView addGestureRecognizer:panGestureRecognizer];
}
</pre>
<p>Now, let&#x2019;s declare and implement the method we set as the action that should be taken when the pan gesture will happen. In the private interface section, add this:</p>
<pre lang="objc">@interface PanViewController ()

-(void)moveViewWithGestureRecognizer:(UIPanGestureRecognizer *)panGestureRecognizer;

@end
</pre>
<p>As I have already said, what we want to do here is to drag the test view while we move our finger on the screen. The easiest approach to that would be to update the center point of the view as long as the panning occurs. Let&#x2019;s see how that is translated into code:</p>
<pre lang="objc">-(void)moveViewWithGestureRecognizer:(UIPanGestureRecognizer *)panGestureRecognizer{
    CGPoint touchLocation = [panGestureRecognizer locationInView:self.view];

    self.testView.center = touchLocation;

}
</pre>
<p>Every gesture recognizer contains a method named <em>locationInView:</em>. This method returns a CGPoint value representing the point of the view that the user touched. In our case, by calling this method we manage to get the touched point during dragging, and to make our app aware of the finger&#x2019;s movement. So, what we only need is to set that touch location as the value for the center point of the test view, and that&#x2019;s exactly we perform using the second command above.</p>
<p>Run the app now and place your finger or the mouse pointer on the test view. Then start dragging around and notice how the view follows the movement you make.</p>
<p><img loading="lazy" decoding="async" width="320" height="588" src="http://www.appcoda.com/wp-content/uploads/2014/08/pan_gesture_demo.gif" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3981"></p>
<p>The approach I presented above is simple for the sake of the tutorial. In a real application, you might want to enrich the movement of the view by adding acceleration or deceleration when you start or stop dragging, or anything else you need. It&#x2019;s up to you to apply the proper logic in the action method you implement.</p>
<p>At the beginning of this section, I said that there is a special method of the <em>UIPanGestureRecognizer</em> class named <em>velocityInView:</em>. Up to this point we totally ignored it, but now we&#x2019;ll see how we can access it and get the data it provides. For the sake of the demo, return to the Interface Builder by clicking on the <em>Main.storyboard</em> file. Locate the <em>Pan view controller scene</em>, and add two labels with the following attributes:</p>
<h3>Label #1</h3>
<ul>
<li><strong>Frame</strong>: X=20, Y=445, Width=280, Height=21</li>
<li><strong>Text</strong>: Nothing (empty)</li>
<li><strong>Font size</strong>: 14pt</li>
</ul>
<h3>Label #2</h3>
<ul>
<li><strong>Frame</strong>: X=20, Y=479, Width=280, Height=21</li>
<li><strong>Text</strong>: Nothing (empty)</li>
<li><strong>Font size</strong>: 14pt</li>
</ul>
<p>As you may suspect, we are going to use these two labels to display the velocity in the horizontal and vertical axis respectively. But before we do so, we must create and connect two IBOutlet properties to these labels. So, open the <em>PanViewController.h</em> file and add the next two lines:</p>
<pre lang="objc">@interface PanViewController : UIViewController

...

@property (weak, nonatomic) IBOutlet UILabel *horizontalVelocityLabel;

@property (weak, nonatomic) IBOutlet UILabel *verticalVelocityLabel;

@end
</pre>
<p>Go back to the Interface Builder, and perform the appropriate connections.</p>
<p>Now, open the <em>PanViewController.m</em> file, and go to our private action method named <em>moveViewWithGestureRecognizer:</em>. We will add some code here that will enable us to get the velocity of the drag as a CGPoint value, and then we will extract the velocity on each axis out of this one. Remember that the velocity is expressed in points per second. Let&#x2019;s see the method:</p>
<pre lang="objc">-(void)moveViewWithGestureRecognizer:(UIPanGestureRecognizer *)panGestureRecognizer{
    ...    

    CGPoint velocity = [panGestureRecognizer velocityInView:self.view];

    self.horizontalVelocityLabel.text = [NSString stringWithFormat:@&quot;Horizontal Velocity: %.2f points/sec&quot;, velocity.x];
    self.verticalVelocityLabel.text = [NSString stringWithFormat:@&quot;Vertical Velocity: %.2f points/sec&quot;, velocity.y];

}
</pre>
<p>The value returned by the <em>velocityInView:</em> method is stored to a CGPoint structure. Then by simply accessing the X and Y properties of that structure, we manage to get the horizontal and vertical velocity. To keep things simple here, we just display these values, but in a real application the velocity would be useful if only you would perform calculations based on it.</p>
<p>By running the app again you can see how &#x201C;fast&#x201D; the test view is moved around the screen while you drag it.</p>
<p><img loading="lazy" decoding="async" width="320" height="588" src="http://www.appcoda.com/wp-content/uploads/2014/08/pan_gesture_demo_2.gif" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3980"></p>
<h2>Pinch Gesture Recognizer</h2>
<p>The pinch gesture is useful for changing the transform of a view by scaling it up or down. The most characteristic example of that gesture can be found in the Photos app, where you pinch to zoom in and out. Here we won&#x2019;t add an image view with an image in it, we&#x2019;ll just use a simple view. However, what we&#x2019;ll do here apply to all views (including image views) in which you want to change their scale value. The great difference that the pinch gesture has compared to the previous gesture recognizers, is the fact that it requires two fingers to be used in order to perform the gesture.</p>
<p>As we did in the previous sections, we will begin by adding a test view to the Interface Builder. On the Project Navigator, click on the <em>Main.storyboard</em> file and then locate the <em>Pinch view controller scene</em>. Next, from the Object Library drag a view object (UIView) to the canvas, and set the next attributes:</p>
<ul>
<li><strong>Frame</strong>: X=85, Y=209, Width=150, Height=150</li>
<li><strong>Background Color</strong>: R=215, G=116, B=52 (or any other color you like)</li>
</ul>
<p><img loading="lazy" decoding="async" width="403" height="395" src="http://www.appcoda.com/wp-content/uploads/2014/08/t19_16_pinch_gesture_testview.png" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-4000" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t19_16_pinch_gesture_testview.png 403w, https://www.appcoda.com/content/images/wordpress/2014/08/t19_16_pinch_gesture_testview-306x300.png 306w" sizes="(max-width: 403px) 100vw, 403px"></p>
<p>Now open the <em>PinchViewController.h</em> file, and declare an IBOutlet property:</p>
<pre lang="objc">@interface PinchViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *testView;

@end
</pre>
<p>Finally, in the Interface Builder connect that property to the test view you just added.</p>
<p>Similarly to the previous cases, we&#x2019;ll begin the implementation in the <em>viewDidLoad</em> method in the <em>PinchViewController.m</em> file. What we only have to do is to initialize a pinch gesture recognizer object, and then add it to the test view:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchWithGestureRecognizer:)];
    [self.testView addGestureRecognizer:pinchGestureRecognizer];
}
</pre>
<p>Now, we must declare the <em>handlePinchWithGestureRecognizer:</em> method, and then define it. First, go to the private class section:</p>
<pre lang="objc">@interface PinchViewController ()

-(void)handlePinchWithGestureRecognizer:(UIPinchGestureRecognizer *)pinchGestureRecognizer;

@end
</pre>
<p>According to what I said in the beginning of this part, we will modify the transform of the test view by changing the scale value. That action will result in a zoom in/out effect, and as you&#x2019;ll see, it&#x2019;s just a matter of a single line:</p>
<pre lang="objc">-(void)handlePinchWithGestureRecognizer:(UIPinchGestureRecognizer *)pinchGestureRecognizer{
    self.testView.transform = CGAffineTransformScale(self.testView.transform, pinchGestureRecognizer.scale, pinchGestureRecognizer.scale);

}
</pre>
<p>In this example we know which is the view that the pinch gesture was applied to (the <em>testView</em> view), so we access it directly. However, there will be times that you will need to access the pinched view in a more generic way. In that case, you can avoid the direct usage of the the view that was pinched as shown above, if you simply use the <em>view</em> property of the <em>pinchGestureRecognizer</em> parameter object. This property is actually the view that the pinch gesture happened to. Therefore, the above command could be written as follows too:</p>
<pre lang="objc">pinchGestureRecognizer.view.transform = CGAffineTransformScale(pinchGestureRecognizer.view.transform, pinchGestureRecognizer.scale, pinchGestureRecognizer.scale);
</pre>
<p>Now we are almost ready to test it. I&#x2019;m saying almost, before we need to add one more command that it&#x2019;s not obvious at the beginning, but you understand that you need it after having tested the above at least once. So, complete the above method by adding this:</p>
<pre lang="objc">-(void)handlePinchWithGestureRecognizer:(UIPinchGestureRecognizer *)pinchGestureRecognizer{
    ...

    pinchGestureRecognizer.scale = 1.0;
}
</pre>
<p>It&#x2019;s necessary to reset the scale value of the pinch gesture recognizer object, otherwise the result won&#x2019;t be the expected one; the scaling will look chaotic. With this simple line, we manage to achieve a smoother behaviour.</p>
<p>Now you can run the app and test the pinch gesture. Act as you do to photos when zooming in and out, and see how our test view reacts to your movements.</p>
<p><img loading="lazy" decoding="async" width="320" height="588" src="http://www.appcoda.com/wp-content/uploads/2014/08/pinch_gesture_demo.gif" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3982"></p>
<h2>Rotation Gesture Recognizer</h2>
<p>The rotation gesture recognizer has great similarities to the pinch gesture recognizer, as it requires two fingers in order for the gesture to be successful, and it changes the transform of the view that is applied to by modifying its rotation. Usually, the rotation gesture is used in combination to other gestures, but not only.</p>
<p>In this part we are going to perform almost the same steps we did in the pinch gesture recognizer section. Therefore, open the Interface Builder, and go to the <em>Rotation view controller scene</em>. From the Object Library, drag and drop a view to the canvas with the following attributes:</p>
<ul>
<li><strong>Frame</strong>: X=85, Y=209, Width=150, Height=150</li>
<li><strong>Background Color</strong>: R=215, G=116, B=52 (or any other color you like)</li>
</ul>
<p>Next, in the <em>RotationViewController.h</em> file declare the following IBOutlet property&#x2026;</p>
<pre lang="objc">@interface RotationViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *testView;

@end
</pre>
<p>&#x2026; and then return to the Interface Builder to connect it to the view.</p>
<p>Going to the <em>RotationViewController.m</em> file now, head to the <em>viewDidLoad</em> directly. As we did to all the previous parts, our coding work will start at this point. Here, we will just create a new rotation gesture recognizer object and we will add it to the test view.</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    UIRotationGestureRecognizer *rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotationWithGestureRecognizer:)];
    [self.testView addGestureRecognizer:rotationGestureRecognizer];
}
</pre>
<p>As always, our next step is to declare the private method:</p>
<pre lang="objc">@interface RotationViewController ()

-(void)handleRotationWithGestureRecognizer:(UIRotationGestureRecognizer *)rotationGestureRecognizer;

@end
</pre>
<p>Finally, let&#x2019;s implement it. Here, we will use the <em>CGAffineTransformRotate</em> method to change the rotate value of the transform of the test view. As you will see in the next code, the <em>rotation</em> property of the <em>rotationGestureRecognizer</em> gets its initial value so as to avoid unexpected behaviour.</p>
<pre lang="objc">-(void)handleRotationWithGestureRecognizer:(UIRotationGestureRecognizer *)rotationGestureRecognizer{
    self.testView.transform = CGAffineTransformRotate(self.testView.transform, rotationGestureRecognizer.rotation);

    rotationGestureRecognizer.rotation = 0.0;
}
</pre>
<p>Run the app now, and make sure to select the last tab of the tab bar controller. Then use two fingers to rotate the view to either a clockwise or counter-clockwise direction.</p>
<p><img loading="lazy" decoding="async" width="320" height="588" src="http://www.appcoda.com/wp-content/uploads/2014/08/rotation_gesture_demo.gif" alt="Using Gesture Recognizers to Handle Pinch, Rotate, Pan, Swipe and Tap Gestures" class="aligncenter size-full wp-image-3983"></p>
<h2>Other Gesture Recognizers</h2>
<p>Beyond the gesture recognizers we met in the previous parts of the tutorial, there are two more that I&#x2019;m going to just mention. We won&#x2019;t see their details for two reasons: They are used more rarely and have similarities to gesture recognizers that we have already seen. So, let&#x2019;s go through them shortly.</p>
<p>The first one is the <em>long press gesture recognizer</em>, and the respective class is the <em>UILongPressGestureRecognizer</em>*. As its name suggests, an object of that class monitors for press on a view that lasts for a some period, and not as long as a tap lasts. This class contains three important properties:</p>
<ul>
<li><em>minimumPressDuration</em>: With this one, you specify the minimum time period that should elapse until the gesture to be considered valid.</li>
<li><em>numberOfTouchesRequired</em>: By using this property, you specify how many fingers are required for the gesture. Usually just one finger is fine, but it&#x2019;s up to you to decide.</li>
<li><em>allowableMovement</em>: This property defines an area that the fingers should move during pressing. When using that gesture, the fingers must remain as stable and steady to the touch point as possible, otherwise the gesture fails.</li>
</ul>
<p>So, if you want to use that gesture recognizer, always keep in mind that you must set valid values to the above properties.</p>
<p>The second gesture recognizer that I will just mention, is the <em>screen edge pan gesture recognizer</em>. The <em>UIScreenEdgePanGestureRecognizer</em> class is new in iOS 7, and it works just like the swipe gesture recognizer, with one great difference though: The finger movement should begin near the edge of the screen. An example of this one can be found in the Safari app, where you can move your finger from the left edge of the screen towards right to go to the previous page. Also, navigation controller supports this gesture recognizer by default. There&#x2019;s one special property that should be set before this gesture recognizer is used, named <em>edges</em>. Using it, you must specify the edge from which the gesture should begin.</p>
<h2>Summary</h2>
<p>When there is a lack of experience in working with gesture recognizers, then it&#x2019;s possible to look intimidating to many developers. However, as you have seen in this tutorial, this is more than a 100% false. Dealing with gesture recognizers is more than easy and quite straightforward. When used in applications, they attach a more advanced level of user interaction and user experience ultimately. Each example of this tutorial has been really simple, but that&#x2019;s what exactly what you need to know even when developing larger applications. Anyway, if you are new to all this, or if you have been feeling uncomfortable with gesture recognizers, then I really hope to have helped you to understand them. Don&#x2019;t be scared to add gestures to your apps, and of course, experiment as much as possible. Lastly, use the comments area to share your thoughts with us, or just&#x2026; make a gesture!</p>
<p>For your reference, you can <a href="https://www.dropbox.com/s/s9e9e8d69rqktzw/GesturesDemo.zip?dl=0&amp;ref=appcoda.com">download the complete Xcode project from here</a>.</p>

<!--kg-card-end: html-->
]]></content:encoded></item><item><title><![CDATA[Understanding Key-Value Observing and Coding]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>In programming, one of the most commonly accepted facts is that the flow of a program depends on the value of the various variables and properties you use. You just have to think how many times during an application development you have to check for your properties&#x2019; values, and</p>]]></description><link>https://www.appcoda.com/understanding-key-value-observing-coding/</link><guid isPermaLink="false">66612a0f166d3c03cf01137e</guid><category><![CDATA[iOS Programming]]></category><category><![CDATA[Objective C]]></category><dc:creator><![CDATA[Gabriel Theodoropoulos]]></dc:creator><pubDate>Wed, 13 Aug 2014 00:52:22 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2014/08/kvo-featured.png" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://www.appcoda.com/content/images/wordpress/2014/08/kvo-featured.png" alt="Understanding Key-Value Observing and Coding"><p>In programming, one of the most commonly accepted facts is that the flow of a program depends on the value of the various variables and properties you use. You just have to think how many times during an application development you have to check for your properties&#x2019; values, and based on them to drive the execution of the code to one or another way. Even more, think of how many times you need to check if an object has been added to an array, or if it has been removed from it. So, being aware of the changes that happen to the properties of your classes is a vital part of the programming process.</p>
<p>There are various ways that let us be notified when a property gets changed. For example, if you have a method to set a property&#x2019;s value, or you just override a setter method, you can send a <em>notification</em> (<em>NSNotification</em>) to notify an observer about that change, and then perform the proper actions based on the value that was set. If you are familiarized with notifications, then using them would not be a problem at all if you would want to use them for being aware about changes in properties, but the truth is that doing so for a great number of properties would require to send and observe for a great number of notifications as well, and that could lead to a lot of extra code writing.</p>
<p><img loading="lazy" decoding="async" width="800" height="282" src="http://www.appcoda.com/wp-content/uploads/2014/08/kvo-featured.png" alt="Understanding Key-Value Observing and Coding" class="aligncenter size-full wp-image-3946" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/kvo-featured.png 800w, https://www.appcoda.com/content/images/wordpress/2014/08/kvo-featured-600x211.png 600w" sizes="(max-width: 800px) 100vw, 800px"></p>
<p>Nevertheless, there is a much better way to observe for changes in properties, and Apple uses it a lot in its own software. That way is not used a lot by programmers because it seems hard to be learnt, however this is not true. Once you get to know it, you&#x2019;ll probably love it and you&#x2019;ll see that it&#x2019;s much effortless and easier to track down changes on single properties or collections, such as arrays. This method is called <strong>Key-Value Observing</strong>, but is mostly known as <strong>KVO</strong>.</p>
<p>Key-Value Observing (KVO) is related directly to another powerful and important mechanism, named <strong>Key-Value Coding</strong>, or <strong>KVC</strong>. Actually, any property you want to observe for changes must be Key-Value Coding compliant, but we will talk more about that later. The important thing for now is to make clear that both of them provide a really powerful and efficient way to write code, and knowing how to handle them can definitely turn you into a more skilled and advanced programmer.</p>
<p>My goal in this tutorial is to walk you through the basics of both of them, and to show you step by step how they can be used. Covering all the aspects regarding these topics in one tutorial is not possible to happen, however after you have finished this one you will be able to manage them efficiently, and you will know what to look for if you need more details on them.</p>
<p>Before we take off and start examining their insides, I should necessarily mention that we will begin our journey from the Key-Value Coding mechanism. It&#x2019;s necessary to know what it is and how it is used before we proceed to the Key-Value Observing mechanism, as the first is prerequisite for the second. So, if you are ready, let&#x2019;s get started!</p>
<h2>Demo App Overview</h2>
<p>As always, this section is dedicated to the description of what the demo app is all about. So, I will start talking about it, highlighting a special characteristic the app will have. That is the fact that we won&#x2019;t do any visual work at all, neither we will work with the Simulator or a device. Actually, the results of our implementation will be displayed on the console only.</p>
<p>Being more detailed, the contents of this tutorial are best suited to a <em>command line tool</em> application, as our topic concerns a clearly programming concept, for which we won&#x2019;t create one sample app from scratch. Instead, we will be moving by implementing many small examples that demonstrate exactly the point of each discussed aspect of our topic, and we will use <em>NSLog</em> commands to output the results of our work. Nevertheless, we are still going to create a single view iOS application, but we&#x2019;ll use no views or subviews to input and output any kind of data. The default view controller&#x2019;s view will just remain empty.</p>
<p>The reason that made me choose an empty iOS application instead of a command line application is simple: I want you to feel comfortable by working to a familiar environment. KVC and KVO are surely new concepts for many of you, so I would like you to focus on these only. I wouldn&#x2019;t like to distract you by making you to work for first time to a command line application. Methods like <em>viewDidLoad</em>, <em>viewWillAppear:</em>, etc., are definitely much more familiar to you (even though I must admit that I would prefer to create a command line app).</p>
<p>So, as I said we will be using only <em>NSLog</em> commands to output the results of our work. Besides that, we are going to create a couple of classes for the sake of the tutorial. The first one will exist for demonstration reasons only, while the second class can be used as a reusable code to your own apps. Generally speaking, by keeping things simple, it will be easier for you to get the point of the Key-Value Coding and Key-Value Observing.</p>
<h2>Creating the Sample App</h2>
<p>So, the first step is to create a new project, therefore go and launch Xcode and select to create a new project. To the guide that appears, select the <strong>Single View Application</strong> template, in the <strong>Application</strong> category under the <strong>iOS</strong> section.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/08/t18_1_create_project_1.jpg" alt="Understanding Key-Value Observing and Coding" class="aligncenter size-full wp-image-3937" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t18_1_create_project_1.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/08/t18_1_create_project_1-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Proceed to the next step, and in the <strong>Product Name</strong> field set the <strong>KVCODemo</strong> name. Leave everything else as it is, and go to the last step, where you should choose a directory to save the project, and you&#x2019;re done.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/08/t18_2_create_project_2.jpg" alt="Understanding Key-Value Observing and Coding" class="aligncenter size-full wp-image-3938" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t18_2_create_project_2.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/08/t18_2_create_project_2-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>The project is now ready!</p>
<h2>Key-Value Coding</h2>
<p>Here is the definition of the Key-Value Coding according to Apple&#x2019;s official documentation:</p>
<p><em>Key-value coding is a mechanism for accessing an object&#x2019;s properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables.</em></p>
<p>What does this mean? Well, let&#x2019;s see it through some simple examples:</p>
<p>Let&#x2019;s suppose that we have a property named <em>firstname</em>, and we want to assign the value <em>John</em> to it. Normally, what we would write in code to do it is this:</p>
<pre lang="objc">self.firstname = @&quot;John&quot;;
</pre>
<p>or this:</p>
<pre lang="objc">_firstname = @&quot;John&quot;;
</pre>
<p>Quite familiar, right? Now, using the KVC mechanism the above assignment would look like the next one:</p>
<pre lang="objc">[self setValue:@&quot;John&quot; forKey:@&quot;firstname&quot;];
</pre>
<p>If you look closely, this looks similar to the way we set values to dictionaries, or when converting scalar values and structs to <em>NSValue</em> objects. As you see, we set the value <em>John</em> for the key <em>firstname</em>. One more example:</p>
<pre lang="objc">[someObject.someProperty setText:@&quot;This is a text&quot;];
</pre>
<p>Using KVC:</p>
<pre lang="objc">[self setValue:@&quot;This is a text&quot; forKeyPath:@&quot;someObject.someProperty.text&quot;];
</pre>
<p>In both of these examples, instead of directly setting the value (first example) to the property or use the setter method (second example) of the property, we simply match values to keys or keypaths (more about keys and keypaths in just a moment). As you assume, because we use keys and values, the above technique is called Key-Value Coding.</p>
<p>So, returning to Apple&#x2019;s definition, you notice that we use strings (the keys) to indirectly access the properties we want to assign values to, instead of doing so directly. On the other hand now, to get values from KVC properties, we would write something like that:</p>
<pre lang="objc">NSLog(@&quot;%@&quot;, [self valueForKey:@&quot;firstname&quot;];
</pre>
<p>Now that you have started getting into the point, let&#x2019;s discuss about some important stuff before we see an actual example on Xcode. First of all, there is an informal protocol, named <em>NSKeyValueCoding</em>, and your class (or classes) must comply with it if you want to use KVC. If your class is a subclass of the <em>NSObject</em> though, then you are already set, because <em>NSObject</em> complies to that protocol.</p>
<p>Besides that, as you saw in the above two examples we used two different methods to set the values to properties. The first one is the <em>setValue:forKey:</em> and the second is the <em>setValue:forKeyPath:</em>. The difference is that the first method expects a key (which is a string value), while the second expects a keypath (also a string value). So, what is a key and what a keypath?</p>
<p>Simply put, the <em>key</em> specifies a single property, the one we want to set a value to or get one from, so its name should be similar to the property&#x2019;s one. In our example, we had the <em>firstname</em> property, and that was exactly the key we used when we set its value using the KVC.</p>
<p>A <em>keypath</em> is always formed using the dot syntax, so it&#x2019;s not a single word, and represents all the properties of an object that should be traversed until the desired one is found (speaking totally non-technically so as to make things clear, I would say that the keypath looks for the subproperty of the subproperty of the &#x2026; (and so on) &#x2026; of an object). For example, the <em>someObject.someProperty.text</em> keypath we set to the second example above refers to the <em>text</em> property of the <em>someProperty</em> of the <em>someObject</em> object.</p>
<p>With all that said, it&#x2019;s time to go to Xcode and see some more examples there. Don&#x2019;t worry if things look still obscure to you, everything will become lighter as we move on.</p>
<p>On Xcode, begin by creating a new class. To do so, open the <strong>File &gt; New &gt; File&#x2026;</strong> menu, and in the window that appears select the <strong>Objective-C class</strong> as the template for our new file.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/08/t18_3_add_file1.jpg" alt="Understanding Key-Value Observing and Coding" class="aligncenter size-full wp-image-3939" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t18_3_add_file1.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/08/t18_3_add_file1-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Next, go to the second step and set the <strong>NSObject</strong> value to the <strong>Subclass of</strong> field. In the <strong>Class</strong> textfield, specify the <strong>Children</strong> value as the name of the new class.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/08/t18_4_add_file2.jpg" alt="Understanding Key-Value Observing and Coding" class="aligncenter size-full wp-image-3940" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t18_4_add_file2.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/08/t18_4_add_file2-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Get finished with the guide, and let Xcode to create the new class and add the couple new files to the project. In the class we just created we are going to add properties regarding the name and the age of a hypothetic person&#x2019;s children, and the way we will use it is perfect to demonstrate all the major aspects of the Key-Value Coding.</p>
<p>Now, open the <em>Children.h</em> file and modify it as shown next. As you&#x2019;ll see, we add only two properties, one for the name and one for the age of the child represented by an instance of that class.</p>
<pre lang="objc">@interface Children : NSObject

@property (nonatomic, strong) NSString *name;

@property (nonatomic) NSUInteger age;

@end
</pre>
<p>Next, open the <em>Children.m</em> file, and initialise the above two properties:</p>
<pre lang="objc">@implementation Children

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.name = @&quot;&quot;;
        self.age = 0;
    }
    return self;
}   

@end
</pre>
<p>It is time to see KVC in action now. Open the <em>ViewController.m</em> file and at the top of it import the header of the <em>Children</em> class:</p>
<pre lang="objc">#import &quot;Children.h&quot;
</pre>
<p>Next, declare three objects of the <em>Children</em> class to the private class section as it&#x2019;s shown below:</p>
<pre lang="objc">@interface ViewController ()

@property (nonatomic, strong) Children *child1;

@property (nonatomic, strong) Children *child2;

@property (nonatomic, strong) Children *child3;

@end
</pre>
<p>Then, head to the <em>viewDidLoad</em> method, where we will initialise the first object:</p>
<pre lang="objc">- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.child1 = [[Children alloc] init];
}
</pre>
<p>If we assign values to the <em>name</em> and <em>age</em> properties of the <em>child1</em> object, and then show them on the debugger as follows&#x2026;</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    self.child1.name = @&quot;George&quot;;
    self.child1.age = 15;

    NSLog(@&quot;%@, %d&quot;, self.child1.name, self.child1.age);

}
</pre>
<p>&#x2026; then we will get the expected output:</p>
<pre lang="objc">George, 15
</pre>
<p>Now, let&#x2019;s try to use the Key-Value Coding method to do the same thing. If you want, either comment out or delete the previous lines in the <em>viewDidLoad</em>, just make sure to leave the <em>child1</em> object initialisation intact.</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    [self.child1 setValue:@&quot;George&quot; forKey:@&quot;name&quot;];
    [self.child1 setValue:[NSNumber numberWithInteger:15] forKey:@&quot;age&quot;];

    NSString *childName = [self.child1 valueForKey:@&quot;name&quot;];
    NSUInteger childAge = [[self.child1 valueForKey:@&quot;age&quot;] integerValue];

    NSLog(@&quot;%@, %d&quot;, childName, childAge);

}
</pre>
<p>In the first couple of rows we set the desired values to both properties using the <em>setValue:forKey:</em> method. Pay attention to the fact that the age is a number, therefore it cannot be passed directly as an argument to that method. Instead, we must convert it to a <em>NSNumber</em> object first. Besides that, watch that the key strings are the same to the properties&#x2019;s names.</p>
<p>Next, we perform the exact opposite task. We extract the values out of the properties using the <em>valueForKey:</em> method, and we assign them to two local variables. Focusing on the age again, notice that we want to get an unsigned integer value, so we convert the returned data type from <em>NSNumber</em> to <em>NSInteger</em>.</p>
<p>Finally, we display everything to the debugger. The output in this case is similar to the previous one:</p>
<pre lang="objc">George, 15
</pre>
<p>That&#x2019;s great, but you may ask yourself if it actually worths it to write the extra lines. Well, as you&#x2019;ll find out next when we&#x2019;ll talk about the Key-Value Observing, yes it is.</p>
<p>Now, replace this line&#x2026;</p>
<pre lang="objc">[self.child1 setValue:@&quot;George&quot; forKey:@&quot;name&quot;];
</pre>
<p>&#x2026; with this one:</p>
<pre lang="objc">[self.child1 setValue:@&quot;George&quot; forKey:@&quot;namee&quot;];
</pre>
<p>In case you read too fast and you don&#x2019;t see the modification, there&#x2019;s an extra &#x201C;;e&#x201D;; letter to the key string. If you run the app once again then&#x2026; Boom! The app crashes! Here&#x2019;s a screenshot from the debugger:</p>
<p><img loading="lazy" decoding="async" width="600" height="72" src="http://www.appcoda.com/wp-content/uploads/2014/08/t18_5_crash.jpeg" alt="Understanding Key-Value Observing and Coding" class="aligncenter size-full wp-image-3941"></p>
<p>The actual message before all that bunch with the technical information says:</p>
<pre lang="objc">Terminating app due to uncaught exception &apos;NSUnknownKeyException&apos;, reason: &apos;[<children 0x8b91840> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.&apos;
</children></pre>
<p>This crash message is quite explanatory. In simple words, it&#x2019;s telling us that the app crashed because no property found matching to the key <em>namee</em>. Okay, no big deal as we can go back to our code and fix this error. However, let&#x2019;s see the bottom line here: When writing KVC-compliant code it&#x2019;s really important to take care so the key strings actually match to the property names, otherwise the app will simply fall apart. This is not a case when dealing directly with properties, as there&#x2019;s no chance to do any mistake on their names; the compiler would throw an error in such a case which would drive us to fix it.</p>
<p>With all the above, we have managed to see how to write KVC-styled code, and how to set and get values using keys. Also, we have seen and underlined what happens if a key name is mistyped. Now, let&#x2019;s extend our example a bit more, and let&#x2019;s see how we can work with keypaths. For starters, go to the <em>Children.h</em> file, and add the next property to the class:</p>
<pre lang="objc">@interface Children : NSObject

...

@property (nonatomic, strong) Children *child;

@end
</pre>
<p>With this, we can represent in code the child of a child (and so on). Return to the <em>ViewController.m</em> file, in the <em>viewDidLoad</em> method. Now, add the next lines that initialize the related objects and assign their initial values:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    self.child2 = [[Children alloc] init];

    [self.child2 setValue:@&quot;Mary&quot; forKey:@&quot;name&quot;];
    [self.child2 setValue:[NSNumber numberWithInteger:35] forKey:@&quot;age&quot;];
    self.child2.child = [[Children alloc] init];
}
</pre>
<p>Nothing new here, we just initialize the <em>child2</em> object of our custom class, we set the values of the name and the age properties, and we then initialize its <em>child</em> object.</p>
<p>The point now is how we can set values to the properties of the <em>child</em> object using the KVC style. According to what we said in the introduction of this tutorial, we must use the <em>setValue:forKeyPath:</em> method to do so. The key that we will provide is going to be a string with the dot syntax to point out the property of the object we want to change. In code:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    [self.child2 setValue:@&quot;Andrew&quot; forKeyPath:@&quot;child.name&quot;];
    [self.child2 setValue:[NSNumber numberWithInteger:5] forKeyPath:@&quot;child.age&quot;];
}
</pre>
<p>It&#x2019;s not difficult, right? Now, simply by adding the next <em>NSLog</em> command, let&#x2019;s see if the assignment was successful:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    NSLog(@&quot;%@, %d&quot;, self.child2.child.name, self.child2.child.age);
}
</pre>
<p>Output:</p>
<pre lang="objc">Andrew, 5
</pre>
<p>Perfect! Now, what if the child of the child has a child too? Let&#x2019;s see this case too (the commands are given altogether):</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    self.child3 = [[Children alloc] init];
    self.child3.child = [[Children alloc] init];
    self.child3.child.child = [[Children alloc] init];

    [self.child3 setValue:@&quot;Tom&quot; forKeyPath:@&quot;child.child.name&quot;];
    [self.child3 setValue:[NSNumber numberWithInteger:2] forKeyPath:@&quot;child.child.age&quot;];

    NSLog(@&quot;%@, %d&quot;, self.child3.child.child.name, self.child3.child.child.age);

}
</pre>
<p>The output is:</p>
<pre lang="objc">Tom, 2
</pre>
<p>Great! So, now you know how to deal with both keys and keypaths, and how to write KVC compliant code. If you want, feel free to write more examples and see what results you get back.</p>
<h2>Observing for Property Changes</h2>
<p>Now that you know the basics of the Key-Value Coding let&#x2019;s move on and let&#x2019;s focus on the Key-Value Observing (KVO). Here we will see what actions should be taken in order to be able to track down changes on properties. First of all, let me introduce you as a list the steps needed to implement KVO:</p>
<ol>
<li>The class of which you want to observe its properties must be KVO compliant. That means:
<ul>
<li>The class must be KVC compliant according to what we have already seen in the introduction and in the previous section.</li>
<li>The class must be able to send notifications either automatically, or manually (we will see more about that later).</li>
</ul>
</li>
<li>The class that will be used to observe the property of another class should be set as <em>observer</em>.</li>
<li>A special method named <em>observeValueForKeyPath:ofObject:change:context:</em> should be implemented to the observing class.</li>
</ol>
<p>Let&#x2019;s see everything one by one. The most important thing when we want to observe for changes of a property, is to <em>make</em> our class observe for these changes. This is done more or less with as with the casual notifications (<em>NSNotifications</em>), but using another method. This method is the <em>addObserver:forKeyPath:options:context</em>. In order to become more specific, I will use our previous example where we used the <em>Children</em> class. In this class we had three properties, the <em>name</em>, the <em>age</em> and the <em>child</em> which was of type <em>Children</em> as well. To observe for the first two of them, here&#x2019;s what is only needed (add the <em>viewWillAppear:</em> method and then write the next lines to it, in the <em>ViewController.m</em> file):</p>
<pre lang="objc">-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    [self.child1 addObserver:self forKeyPath:@&quot;name&quot; options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    [self.child1 addObserver:self forKeyPath:@&quot;age&quot; options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];    
}
</pre>
<p>The parameters the above method accepts are:</p>
<ul>
<li><em>addObserver</em>: This is the observing class, usually the <em>self</em> object.</li>
<li><em>forKeyPath</em>: I guess you can understand what&#x2019;s this for. It is the string you used as a key or a key path and matches to the property you want to observe. Note that you specify here either a single key, or a key path.</li>
<li><em>options</em>: By setting a value other than 0 (zero) to this parameter, you specify what the notification should contain. You can set a single value, or a combination of <em>NSKeyValueObservingOptions</em> values, combining them using the logical or (|). In the above example, we ask from the notifications to contain both the old and the new value of the properties we observe.</li>
<li><em>context</em>: This is a pointer that can be used as a unique identifier for the change of the property we observe. Usually this is set to <em>nil</em> or <em>NULL</em>. We&#x2019;ll see more about this later.</li>
</ul>
<p>Now that we have made our class able to observe for any changes in the above two properties, we must implement the <em>observeValueForKeyPath:ofObject:change:context:</em> method. Its implementation is mandatory, and it has one great disadvantage. That is the fact that is called for every KVO change, and if you observe many properties then you must write a lot of <em>if</em> statements so as to take the proper actions for each property. However, this can be easily overlooked as the benefits of the KVO are greater than this limitation.</p>
<p>Now, let&#x2019;s implement it.</p>
<pre lang="objc">-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    if ([keyPath isEqualToString:@&quot;name&quot;]) {
        NSLog(@&quot;The name of the child was changed.&quot;);
        NSLog(@&quot;%@&quot;, change);
    }

    if ([keyPath isEqualToString:@&quot;age&quot;]) {
        NSLog(@&quot;The age of the child was changed.&quot;);
        NSLog(@&quot;%@&quot;, change);
    }

}
</pre>
<p>As you see, we do nothing special here (for the sake of the demonstration). What we only do, is to determine the property that was changed based on the <em>keyPath</em> parameter, and then to display just a single message along with the dictionary containing the changes that took place. In a real application, you apply all the needed logic to handle all the changes in each case.</p>
<p>Time to test it, don&#x2019;t you think? In the <em>viewWillAppear:</em> method, add the next line:</p>
<pre lang="objc">-(void)viewWillAppear:(BOOL)animated{
    ...

    [self.child1 setValue:@&quot;Michael&quot; forKey:@&quot;name&quot;];
}
</pre>
<p>Let&#x2019;s run the app and let&#x2019;s see what will be displayed on the debugger:</p>
<pre lang="objc">The name of the child was changed.
{
    kind = 1;
    new = Michael;
    old = George;
}
</pre>
<p>Super! After we have set a new value to the <em>name</em> property of the <em>child1</em> object, we received the notification, and the messages we asked for to be displayed were shown on the debugger. As you see, both the previous and the new value are included in the dictionary.</p>
<p>Now, let&#x2019;s change the <em>age</em> property of the <em>child1</em> object to see if the notification will arrive:</p>
<pre lang="objc">-(void)viewWillAppear:(BOOL)animated{
    ...

    [self.child1 setValue:[NSNumber numberWithInteger:20] forKey:@&quot;age&quot;];
}
</pre>
<p>And when we run it:</p>
<pre lang="objc">The age of the child was changed.
{
    kind = 1;
    new = 20;
    old = 15;
}
</pre>
<p>So, everything seems to be working great. From the <em>change</em> dictionary you can extract any value you want (if needed), but the most important of all is that it&#x2019;s super-easy to be notified about changes in properties. If all these look new to you, don&#x2019;t worry. It&#x2019;s all just a matter of habit!</p>
<p>We are going to make everything much more interesting now, simply by adding one more observer for the <em>age</em> property of the <em>child2</em> object. After that, we will assign a new value to that property.</p>
<pre lang="objc">-(void)viewWillAppear:(BOOL)animated{
    ...

    [self.child2 addObserver:self forKeyPath:@&quot;age&quot; options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

    [self.child2 setValue:[NSNumber numberWithInteger:45] forKey:@&quot;age&quot;];
}
</pre>
<p>If we run the app, the output will be this:</p>
<p>The name of the child was changed.<br>
 {<br>
 kind = 1;<br>
 new = Michael;<br>
 old = George;<br>
 }</p>
<pre lang="objc">The age of the child was changed.
{
    kind = 1;
    new = 20;
    old = 15;
}

The age of the child was changed.
{
    kind = 1;
    new = 45;
    old = 35;
}
</pre>
<p>As you notice, we receive two notifications regarding changes to the <em>age</em> property. But that seems confusing, because even though we know the object that each notification belongs to, programmatically we can do nothing to determine the object that sent the notification. So, how do we face that, and how can we programmatically be a 100% sure about the object that the changed property belongs to?</p>
<p>The answer to the above question is one: We will make use of the <em>context</em> argument of the <em>addObserver:forKeyPath:options:context:</em> method. I have already mentioned before that the purpose of the context is to uniquely identify a change on a property, so it&#x2019;s the best tool we have at our disposal. As I have said, the context is a pointer, and it actually points to itself, so the way that is declared is the following:</p>
<pre lang="objc">static void *someContext = &amp;someContext;
</pre>
<p>Note that the context value for each observed property must be a global variable, because it has to be accessible from both the <em>addObserver&#x2026;</em> and the <em>observeValueForKeyPath&#x2026;</em> methods. Let&#x2019;s get back to our example, and let&#x2019;s add a couple of context values. In the <em>ViewController.m</em> file, go at the very top of it, just right before the <em>@interface ViewController ()</em> line. There, add the next two commands:</p>
<pre lang="objc">static void *child1Context = &amp;child1Context;
static void *child2Context = &amp;child2Context;
</pre>
<p>Alternatively, instead of declaring these two as global variables, you could use them as properties of your class, but I consider the first way to be much simpler.</p>
<p>Now, we just have to modify the code in the <em>viewWillAppear:</em> method by setting the proper context value to the <em>addObserver:forKeyPath:options:context:</em> calls. Here it is in one piece:</p>
<pre lang="objc">-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    [self.child1 addObserver:self forKeyPath:@&quot;name&quot; options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:child1Context];
    [self.child1 addObserver:self forKeyPath:@&quot;age&quot; options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:child1Context];

    [self.child1 setValue:@&quot;Michael&quot; forKey:@&quot;name&quot;];
    [self.child1 setValue:[NSNumber numberWithInteger:20] forKey:@&quot;age&quot;];

    [self.child2 addObserver:self forKeyPath:@&quot;age&quot; options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:child2Context];

    [self.child2 setValue:[NSNumber numberWithInteger:45] forKey:@&quot;age&quot;];
}
</pre>
<p>Finally, we have to modify the <em>observeValueForKeyPath:ofObject:change:context:</em> appropriately, so we can programmatically determine the object that sends the notification.</p>
<pre lang="objc">-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    if (context == child1Context) {
        if ([keyPath isEqualToString:@&quot;name&quot;]) {
            NSLog(@&quot;The name of the FIRST child was changed.&quot;);
            NSLog(@&quot;%@&quot;, change);
        }

        if ([keyPath isEqualToString:@&quot;age&quot;]) {
            NSLog(@&quot;The age of the FIRST child was changed.&quot;);
            NSLog(@&quot;%@&quot;, change);
        }
    }
    else if (context == child2Context){
        if ([keyPath isEqualToString:@&quot;age&quot;]) {
            NSLog(@&quot;The age of the SECOND child was changed.&quot;);
            NSLog(@&quot;%@&quot;, change);
        }
    }
}
</pre>
<p>I said before that the drawback of using this method is that you have to write a bunch of <em>if</em> statements, and now you can see this fact. Anyway, you can clearly understand how easy it is to identify a property that was changed based on the context and the key path. Running the app once again, we get the next output:</p>
<pre lang="objc">The name of the FIRST child was changed.
{
    kind = 1;
    new = Michael;
    old = George;
}

The age of the FIRST child was changed.
{
    kind = 1;
    new = 20;
    old = 15;
}

The age of the SECOND child was changed.
{
    kind = 1;
    new = 45;
    old = 35;
}
</pre>
<p>Much better now! We modified and messages in such way, so they are more explanatory and of course, we managed to programmatically specify each changed property.</p>
<p>Lastly and before we reach at the end of this chapter, it&#x2019;s also quite important at some point to remove the observers you add. There is not a recipe on where you should do that. For instance, in many cases it would be useful to do that in the <em>observeValueForKeyPath:ofObject:change:context:</em>, after you have handled a received notification. In other cases, you should do so upon the dismissal of a view controller. Generally, it&#x2019;s up to your application&#x2019;s structure the decision you will make about that. In this example, we will do it in the <em>viewWillDissapear:</em> method. Here it is:</p>
<pre lang="objc">-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    [self.child1 removeObserver:self forKeyPath:@&quot;name&quot;];
    [self.child1 removeObserver:self forKeyPath:@&quot;age&quot;];
    [self.child2 removeObserver:self forKeyPath:@&quot;age&quot;];
}
</pre>
<p>So, now you know the most important steps you should make when you want to apply Key-Value Observing logic to your application. As you found out, the rules that should be followed are simple, and all the hard work of monitoring for changes and sending notifications is done by iOS itself. However, there are more details we should discuss about, but the knowledge you acquired up to this point is the most significant.</p>
<h2>Automatic and Manual Notifications</h2>
<p>By default, the system sends a notification every time a property gets changed when you observe using KVO. This is suitable in most cases, however there are times that we don&#x2019;t want to get a notification once a change has happened, but after a bunch of changes have taken place in multiple properties or at a later time. Thankfully, iOS SDK provides us with some quite convenient methods that gives us control over the notifications, so we can manually send them whenever it&#x2019;s actually needed. Before we get into more details, let me just say that using the method you&#x2019;ll see right next is not mandatory. On the contrary, you may implement it if and when it is really necessary.</p>
<p>Getting into the point now, in order to control the notifications that are sent upon property changes, you must implement the <em>automaticallyNotifiesObserverForKey:</em> class method. The parameter it accepts is a string representation of the key of the property for which you need to control the notification, and it returns a boolean value. In case that you don&#x2019;t want a notification to be sent after the observed property&#x2019;s value has been changed, then the method must return NO. In any other case, you should let iOS decide about the notifications (you&#x2019;ll see how in the example that follows).</p>
<p>In practice, let&#x2019;s suppose that we don&#x2019;t want a notification to be posted when the <em>name</em> property of the <em>Children</em> class get changed. With that in mind, here&#x2019;s the implementation of that method in the <em>Children</em> class (<em>Children.m</em> file):</p>
<pre lang="objc">+(BOOL)automaticallyNotifiesObserversForKey:(NSString *)key{
    if ([key isEqualToString:@&quot;name&quot;]) {
        return NO;
    }
    else{
        return [super automaticallyNotifiesObserversForKey:key];
    }
}
</pre>
<p>I believe that the method is quite straightforward. In the <em>else</em> clause, we call the same method using the <em>super</em> class in order to let iOS handle all the keys that we haven&#x2019;t explicitly added here, and the value that we get back is the one that we return at the end.</p>
<p>If you run the app at this point, you&#x2019;ll find out that no message regarding the name changing is appeared on the debugger. Of course, this is what we desire, so we&#x2019;ve managed to achieve our goal. But, have we really done it?</p>
<p>Well, as you understand by returning NO in the above method for the specific key, we&#x2019;ve only managed to stop the relevant notifications from being sent. And of course, this doesn&#x2019;t mean manual notifications, it means no notifications at all! In order to send a notification when we decide so, we must use two other methods. These are the <em>willChangeValueForKey:</em> and the <em>didChangeValueForKey:</em>. When using them, the <em>willChangeValueForKey:</em> must be called first, then the new value must be assigned to the property, while the <em>didChangeValueForKey:</em> should be called at the end.</p>
<p>Back in the action again, go to the <em>ViewController.m</em> file and then to the <em>viewWillAppear:</em> method. Next, replace this line:</p>
<pre lang="objc">[self.child1 setValue:@&quot;Michael&quot; forKey:@&quot;name&quot;];
</pre>
<p>with these three:</p>
<pre lang="objc">[self.child1 willChangeValueForKey:@&quot;name&quot;];
self.child1.name = @&quot;Michael&quot;;
[self.child1 didChangeValueForKey:@&quot;name&quot;];
</pre>
<p>If you run the app now, the message regarding the name change is appeared on the debugger, and that means that we&#x2019;ve sent the notification manually with success!</p>
<pre lang="objc">The name of the FIRST child was changed.
{
    kind = 1;
    new = Michael;
    old = George;
}
</pre>
<p>Actually, the notification is sent after the <em>didChangeValueForKey:</em> method is invoked, therefore if you don&#x2019;t want to send the notification right after the value assignment, simply get this line:</p>
<pre lang="objc">[self.child1 didChangeValueForKey:@&quot;name&quot;];
</pre>
<p>and place it right to the point that is appropriate for the notification to be sent. For example, if we add the above call at the end of the <em>viewWillAppear:</em> method, then the name change messages will be the last appearing on the debugger when you run the app:</p>
<pre lang="objc">The age of the FIRST child was changed.
{
    kind = 1;
    new = 20;
    old = 15;
}

The age of the SECOND child was changed.
{
    kind = 1;
    new = 45;
    old = 35;
}

The name of the FIRST child was changed.
{
    kind = 1;
    new = Michael;
    old = George;
}
</pre>
<p>That&#x2019;s what exactly we have been expecting from the app! As you can see, we&#x2019;ve managed to control the notification sending point, and all that with a little effort! Note that between the <em>willChangeValueForKey:</em> and the <em>didChangeValueForKey:</em> methods, you can have more than one property values assigned.</p>
<p>The <em>willChangeValueForKey:</em> and the <em>didChangeValueForKey:</em> methods are not mandatory to be used as shown above. They can be implemented in the <em>Children</em> class (or in your own class) as well. In order to see such an example, we will override the <em>setter</em> method of the <em>name</em> property. Before doing so, just comment our or remove these lines in the <em>viewWillAppear:</em> method so we won&#x2019;t face any problem later on:</p>
<pre lang="objc">[self.child1 willChangeValueForKey:@&quot;name&quot;];
self.child1.name = @&quot;Michael&quot;;
[self.child1 didChangeValueForKey:@&quot;name&quot;];
</pre>
<p>Now, open the <em>Children.m</em> file, and add the following implementation.</p>
<pre lang="objc">-(void)setName:(NSString *)name{
    [self willChangeValueForKey:@&quot;name&quot;];
    _name = name;
    [self didChangeValueForKey:@&quot;name&quot;];
}
</pre>
<p>Back to the <em>ViewController.m</em> now, add the next one as the last command to the <em>viewWillAppear:</em> method:</p>
<pre lang="objc">-(void)viewWillAppear:(BOOL)animated{
    ...

    self.child1.name = @&quot;Michael&quot;;
}
</pre>
<p>Finally, run the app once again. What are you watching on the debugger? The messages about the <em>name</em> property of course after the rest of the notification messages!</p>
<pre lang="objc">The age of the FIRST child was changed.
{
    kind = 1;
    new = 20;
    old = 15;
}

The age of the SECOND child was changed.
{
    kind = 1;
    new = 45;
    old = 35;
}

The name of the FIRST child was changed.
{
    kind = 1;
    new = Michael;
    old = George;
}
</pre>
<p>Awesome, but most importantly, by using the <em>willChangeValueForKey:</em>, the <em>didChangeValueForKey:</em> or by overriding the setter method of the <em>name</em> property, we managed to set the new value directly to it as we would normally do, and to still have the KVO working! Pretty useful, right?</p>
<h2>Working With Arrays</h2>
<p>Arrays is a special case in Key-Value Coding and Key-Value Observing, as there are extra actions that should be performed before you successfully manage to observe for changes made on them. Actually, there are a lot of details regarding the arrays, but here we&#x2019;ll see just the basics and most important things you need to know so you can work with them.</p>
<p>The first thing that you should know is that arrays are not KVC compliant, therefore dealing with them is not as simple as with single properties. There are certain methods regarding the arrays that should be implemented in order to make them KVC compliant, and ultimately to be able to observe any changes on them. So, let&#x2019;s talk about them.</p>
<p>For the sake of the tutorial we will discuss about mutable arrays. However, immutable arrays are handled the same way, except for the fact that fewer methods are needed to be implemented. So, let&#x2019;s suppose that we have a mutable array named <em>myArray</em>. The methods that should be implemented are similar to those we use for inserting, removing, and counting objects usually to an array, but with some differences on their naming (you will get the meaning of that pretty soon). A minimum number of methods is required to be written, so let&#x2019;s see them:</p>
<ul>
<li><em>countOfMyArray</em></li>
<li><em>objectInMyArrayAtIndex:</em></li>
<li><em>insertObject:inMyArrayAtIndex:</em></li>
<li><em>removeObjectFromMyArrayAtIndex:</em></li>
</ul>
<p>All of those methods look familiar, don&#x2019;t they? The new here is that in their names we append the name of our array. Notice that even though the array is named <em>myArray</em>, when it is used in the methods the first letter becomes capital (<em>MyArray</em>). It&#x2019;s obvious that in a real implementation, the <em>MyArray</em> name is replaced by the name of the actual array. Beyond that, there are a few more methods that could be implemented in order to increase performance and flexibility, but here we will stay on them. Of course, when talking about immutable arrays, the last two methods should not be implemented.</p>
<p>There are both good and bad news when making an array KVC compliant. The good news is that Xcode suggests you each method&#x2019;s name once you start typing, so you don&#x2019;t have necessarily to remember them. The bad news however is that you should implement all those methods for every single array you have in your class and you want to observe. Don&#x2019;t worry though, as I am going to show you a technique at the next section that could get you out of trouble very easily.</p>
<p>Now, it&#x2019;s time to go to practice, and to see how everything we discussed so far is actually applied in code. For our purposes, we will add a new mutable array to the <em>Children</em> class that is supposed to contain the names of the siblings of a child. Go to the <em>Children.h</em> file, and add the next declaration:</p>
<pre lang="objc">@interface Children : NSObject

...

@property (nonatomic, strong) NSMutableArray *siblings;

@end
</pre>
<p>Next, open the <em>Children.m</em> file, and in the <em>init</em> method initialize the array:</p>
<pre lang="objc">- (instancetype)init
{
    self = [super init];
    if (self) {
        ...

        self.siblings = [[NSMutableArray alloc] init];
    }
    return self;
}
</pre>
<p>Now we are ready to focus on the methods that should be implemented. Go back to the <em>Children.h</em> file, and add the following method declarations. I would recommend to type them instead of copy-paste them, in order for you to see how Xcode suggests them to you.</p>
<pre lang="objc">@interface Children : NSObject

...

-(NSUInteger)countOfSiblings;

-(id)objectInSiblingsAtIndex:(NSUInteger)index;

-(void)insertObject:(NSString *)object inSiblingsAtIndex:(NSUInteger)index;

-(void)removeObjectFromSiblingsAtIndex:(NSUInteger)index;

@end
</pre>
<p>Notice how the <em>siblings</em> array name is used in the above declarations, and that the first letter is always capital. There is one comment that I would like to do here, and that is that for the <em>insertObject:inSiblingsAtIndex:</em> method, Xcode does not set the type of the objects to the parameters automatically, but it let&#x2019;s you type them according to the kind of data you are going to have in your array. In other words, if you start typing it Xcode will suggest you this:</p>
<pre lang="objc">-(void)insertObject:(<object-type> *)object inSiblingsAtIndex:(<nsuinteger>)index
</nsuinteger></object-type></pre>
<p>&#x2026;and you manually have to go and set the proper types of the parameters. As I said, in our case we are going to add the names of the siblings, so we will set the <em>NSString</em> type. Alternatively, in the first parameter you can specify the <em>id</em> keyword (without the asterisk), which is suitable for any type of data you may have.</p>
<p>Let&#x2019;s implement them now. Open the <em>Children.m</em> file, and add the next code segment. As you will see, what it is written is pretty simple and straightforward.</p>
<pre lang="objc">-(NSUInteger)countOfSiblings{
    return self.siblings.count;
}


-(id)objectInSiblingsAtIndex:(NSUInteger)index{
    return [self.siblings objectAtIndex:index];
}


-(void)insertObject:(NSString *)object inSiblingsAtIndex:(NSUInteger)index{
    [self.siblings insertObject:object atIndex:index];
}


-(void)removeObjectFromSiblingsAtIndex:(NSUInteger)index{
    [self.siblings removeObjectAtIndex:index];
}
</pre>
<p>That&#x2019;s it! Now the <em>siblings</em> array is KVC compliant, so we can track down any changes that happen to it as we normally do with every other property. Of course, we will add and remove data using only the above methods.</p>
<p>Open the <em>ViewController.m</em> file, and go to the <em>viewWillAppear:</em> method. The first step in KVO is to always observe for the desired property, so add the next line at the end of the method (we will observe only for changes to the <em>siblings</em> array of the <em>child1</em> object):</p>
<pre lang="objc">-(void)viewWillAppear:(BOOL)animated{
    ...    

    [self.child1 addObserver:self forKeyPath:@&quot;siblings&quot; options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

}
</pre>
<p>Now, let&#x2019;s add some objects to the array, and then remove one of them:</p>
<pre lang="objc">-(void)viewWillAppear:(BOOL)animated{
    ...

    [self.child1 insertObject:@&quot;Alex&quot; inSiblingsAtIndex:0];
    [self.child1 insertObject:@&quot;Bob&quot; inSiblingsAtIndex:1];
    [self.child1 insertObject:@&quot;Mary&quot; inSiblingsAtIndex:2];
    [self.child1 removeObjectFromSiblingsAtIndex:1];
}
</pre>
<p>Perfect! Not only we implemented the methods needed to make our array KVC compliant, we also used them to add and remove objects. There&#x2019;s one step remaining, and that is to handle the received notification to the <em>observeValueForKeyPath:object:change:context:</em> method. Here&#x2019;s the additional code needed to display on the console the changes that arrive with each notification:</p>
<pre lang="objc">-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    ...
    else{
        if ([keyPath isEqualToString:@&quot;siblings&quot;]) {
            NSLog(@&quot;%@&quot;, change);
        }
    }
}
</pre>
<p>Time to test it&#x2026; Here are the results displayed on the console:</p>
<pre lang="objc">{
    indexes = &quot;<nsindexset: 0x8b92910>[number of indexes: 1 (in 1 ranges), indexes: (0)]&quot;;
    kind = 2;
    new =     (
        Alex
    );
}

{
    indexes = &quot;<nsindexset: 0x8e29ac0>[number of indexes: 1 (in 1 ranges), indexes: (1)]&quot;;
    kind = 2;
    new =     (
        Bob
    );
}

{
    indexes = &quot;<nsindexset: 0x8b92910>[number of indexes: 1 (in 1 ranges), indexes: (2)]&quot;;
    kind = 2;
    new =     (
        Mary
    );
}

{
    indexes = &quot;<nsindexset: 0x8e29ac0>[number of indexes: 1 (in 1 ranges), indexes: (1)]&quot;;
    kind = 3;
    old =     (
        Bob
    );
}
</nsindexset:></nsindexset:></nsindexset:></nsindexset:></pre>
<p>The results are in accordance to our actions. We performed three insertions and one deletion, and that&#x2019;s what exactly the above messages describe. In the first three cases, there is no previous value to display, so only the new one is shown. In the last case, it&#x2019;s shown only the old value, while there&#x2019;s not a new one as we just remove an object.</p>
<h2>A General Approach on Arrays</h2>
<p>Applying KVC and KVO to arrays is not that difficult ultimately according to what we have seen to the previous section, however it requires some extra coding, and if you have several arrays that you need to observe, then the amount of code writing gets increased. Obviously, it would be great if we could minimize that effort, and at the same time to be able to KVO on arrays. Well, actually there is a simple but nice technique. What I will show you in this section is a method that I&#x2019;ve been using in my projects repeatedly for a long time, and after some research on the web I found out that similar techniques are recommended by others too. So, let&#x2019;s go for it.</p>
<p>The big idea on the approach that I will present here, is to create and use an extra class that contains just a mutable array and it implements the necessary methods for making it KVC compliant. Once it&#x2019;s ready, objects of this class can be used to any other classes instead of arrays. The benefits from all that are multiple:</p>
<ul>
<li>The necessary methods we implemented in the previous section don&#x2019;t have to be written more than once.</li>
<li>You can use objects of that class everywhere instead of normal mutable arrays.</li>
<li>Most importantly, it is reusable, meaning that you implement it once and you use it to many projects!</li>
</ul>
<p>In other words, think of it as a mechanism that provides you an advanced version of the mutable arrays. Let&#x2019;s work on it.</p>
<p>Begin by adding a new class to the project. Go to the <strong>File &gt; New &gt; File&#x2026;</strong> menu, and in the guide that appears select the <strong>Objective-C class</strong> option as the template. To the next step, make sure that the <strong>Subclass of</strong> field contains the <strong>NSObject</strong> value, and set the <strong>KVCMutableArray</strong> as the name of the class to the <strong>Class</strong> field. Get finished with the guide and wait until the new files are added to the project.</p>
<p>Go to the <em>KVCMutableArray.h</em> file, and add the next array declaration:</p>
<pre lang="objc">@interface KVCMutableArray : NSObject

@property (nonatomic, strong) NSMutableArray *array;

@end
</pre>
<p>Now, let&#x2019;s create an <em>init</em> method, where we will initialize the array. To do so, open the <em>KVCMutableArray.m</em> file and add the next code segment:</p>
<pre lang="objc">- (instancetype)init
{
    self = [super init];
    if (self) {
        self.array = [[NSMutableArray alloc] init];
    }
    return self;
}
</pre>
<p>Great! This array is going to be the <em>container</em> for all of our data, so its role is very important. Now we have it declared and initialized, we can move to the methods that will make it KVC compliant. Firstly, go to the <em>KVCMutableArray.h</em> file and do the proper declarations:</p>
<pre lang="objc">@interface KVCMutableArray : NSObject

...

-(NSUInteger)countOfArray;

-(id)objectInArrayAtIndex:(NSUInteger)index;

-(void)insertObject:(id)object inArrayAtIndex:(NSUInteger)index;

-(void)removeObjectFromArrayAtIndex:(NSUInteger)index;

-(void)replaceObjectInArrayAtIndex:(NSUInteger)index withObject:(id)object;

@end
</pre>
<p>Notice that I added a new method, the <em>replaceObjectInArrayAtIndex:withObject:</em>, so our class is even more powerful. Besides that, our approach is more general here, so in the <em>insertObject:inArrayAtIndex:</em> method we specified the <em>id</em> instead of a specific data type or class. Once again, notice how the name of the array is used to the methods.</p>
<p>Now, open the <em>KVCMutableArray.m</em> file, and implement them:</p>
<pre lang="objc">-(NSUInteger)countOfArray{
    return self.array.count;
}


-(id)objectInArrayAtIndex:(NSUInteger)index{
    return [self.array objectAtIndex:index];
}


-(void)insertObject:(id)object inArrayAtIndex:(NSUInteger)index{
    [self.array insertObject:object atIndex:index];
}


-(void)removeObjectFromArrayAtIndex:(NSUInteger)index{
    [self.array removeObjectAtIndex:index];
}

-(void)replaceObjectInArrayAtIndex:(NSUInteger)index withObject:(id)object{
    [self.array replaceObjectAtIndex:index withObject:object];
}
</pre>
<p>All implementations are very simple, so our work here is over. The new class is ready!</p>
<p>Let&#x2019;s assume now that in the <em>Children</em> class we want to add and observe a new array, which will contain the names of the cousins of a child. It&#x2019;s obvious that instead of a normal mutable array, we will use an object of the <em>KVCMutableArray</em> class. Without wasting more time, let&#x2019;s open the <em>Children.h</em> file, and let&#x2019;s declare a new property:</p>
<pre lang="objc">@interface Children : NSObject

...

@property (nonatomic, strong) KVCMutableArray *cousins;

@end
</pre>
<p>Xcode will become grumpy, so go at the top of the file and import this:</p>
<pre lang="objc">#import &quot;KVCMutableArray.h&quot;
</pre>
<p>We are fine here, so open the <em>Children.m</em> file and initialize the new object:</p>
<pre lang="objc">- (instancetype)init
{
    self = [super init];
    if (self) {
        ...

        self.cousins = [[KVCMutableArray alloc] init];
    }
    return self;
}
</pre>
<p>And finally, the big step. It&#x2019;s time to try it, so open the <em>ViewController.m</em> file and at the end of the <em>viewWillAppear:</em> method add the next lines:</p>
<pre lang="objc">-(void)viewWillAppear:(BOOL)animated{
    ...

    [self.child1 addObserver:self forKeyPath:@&quot;cousins.array&quot; options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

    [self.child1.cousins insertObject:@&quot;Antony&quot; inArrayAtIndex:0];
    [self.child1.cousins insertObject:@&quot;Julia&quot; inArrayAtIndex:1];
    [self.child1.cousins replaceObjectInArrayAtIndex:0 withObject:@&quot;Ben&quot;];
}
</pre>
<p>Firstly, notice the keypath value we use. Remember that what we want to observe is the array of the <em>KVCMutableArray</em> class, and not the object itself, so we use the dot syntax to specify that. Secondly, to insert new objects we call the custom KVC compliant method we implemented, and lastly we make use of the new method to replace the first object.</p>
<p>The final step:</p>
<pre lang="objc">-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    ...
    else{
        ...

        if ([keyPath isEqualToString:@&quot;cousins.array&quot;]) {
            NSLog(@&quot;%@&quot;, change);
        }
    }
}
</pre>
<p>Ready to test it? If we run it, here are the results we get on the console:</p>
<pre lang="objc">{
    indexes = &quot;<nsindexset: 0x8ba2e60>[number of indexes: 1 (in 1 ranges), indexes: (0)]&quot;;
    kind = 2;
    new =     (
        Antony
    );
}

{
    indexes = &quot;<nsindexset: 0x8ba2e60>[number of indexes: 1 (in 1 ranges), indexes: (1)]&quot;;
    kind = 2;
    new =     (
        Julia
    );
}

{
    indexes = &quot;<nsindexset: 0x8ba2e60>[number of indexes: 1 (in 1 ranges), indexes: (0)]&quot;;
    kind = 4;
    new =     (
        Ben
    );
    old =     (
        Antony
    );
}
</nsindexset:></nsindexset:></nsindexset:></pre>
<p>Excellent! It is what exactly we have been wanted to see. Both new objects are inserted to the array, and the replacement successfully takes place at the end.</p>
<p>So, it seems that the new class we implemented here is a new great tool, which you can wrap up and get with you when you are done with the tutorial. You see how really easy it is to observe for changes on arrays, and all that with almost no effort at all!</p>
<h2>Summary</h2>
<p>Both Key-Value Coding and Key-Value Observing are mechanisms that allow you to create more powerful, more flexible and more efficient applications. These mechanisms are not adopted by a great number of developers, and that&#x2019;s a pity, because even though they look weird at the beginning, at the end it&#x2019;s proved to be very easy to be handled. In this tutorial I made an effort to provide you with a detailed introduction to both the KVC and KVO concepts. What you have learnt here is good enough to let you work with them in your projects, but there is more advanced information you could look up if you want so. It would be impossible to cover everything into one tutorial, but the most you need is here. So, having this post as a guide, I hope you&#x2019;ll manage to use the demonstrated techniques to your projects too, and of course, you can add the last class we created in the previous section to your programming toolbox. Happy Key-Value programming!</p>
<p>For your reference, here is the <a href="https://www.dropbox.com/s/1c4jfnrnxm3gc3l/KVCODemo.zip?ref=appcoda.com">complete Xcode project</a> for your download.</p>

<!--kg-card-end: html-->
]]></content:encoded></item><item><title><![CDATA[Understanding XML and JSON Parsing in iOS Programming]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>One of the most important tasks that a developer has to deal with when creating applications is the data handing and manipulation. Data can be expressed in many different formats, and mastering at least the most known of them consists of a key ability for every single programmer. Speaking for</p>]]></description><link>https://www.appcoda.com/parse-xml-and-json-web-service/</link><guid isPermaLink="false">66612a0f166d3c03cf01137d</guid><category><![CDATA[iOS Programming]]></category><category><![CDATA[Objective C]]></category><dc:creator><![CDATA[Gabriel Theodoropoulos]]></dc:creator><pubDate>Mon, 04 Aug 2014 23:21:58 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2014/08/json-xml-demo-featured.png" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://www.appcoda.com/content/images/wordpress/2014/08/json-xml-demo-featured.png" alt="Understanding XML and JSON Parsing in iOS Programming"><p>One of the most important tasks that a developer has to deal with when creating applications is the data handing and manipulation. Data can be expressed in many different formats, and mastering at least the most known of them consists of a key ability for every single programmer. Speaking for mobile applications specifically now, it&#x2019;s quite common nowadays for them to exchange data with web applications. In such cases, the way that data is expressed may vary, but usually is preferred either the <strong>JSON</strong> or the <strong>XML</strong> format.</p>
<p>iOS SDK provides classes for handling both of them. For managing JSON data, there is the <em>NSJSONSerialization</em> class. This one allows to easily convert a JSON data into a Foundation object (NSArray, NSDictionary), and the other way round. For parsing XML data, iOS offers the <em>NSXMLParser</em> class, which takes charge of doing all the hard work, and through some useful delegate methods gives us the tools we need for handling each step of the parsing.</p>
<p><img loading="lazy" decoding="async" width="800" height="488" src="http://www.appcoda.com/wp-content/uploads/2014/08/json-xml-demo-featured.png" alt="Understanding XML and JSON Parsing in iOS Programming" class="aligncenter size-full wp-image-3927" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/json-xml-demo-featured.png 800w, https://www.appcoda.com/content/images/wordpress/2014/08/json-xml-demo-featured-491x300.png 491w" sizes="(max-width: 800px) 100vw, 800px"></p>
<p>Focusing a bit on each class separately, there&#x2019;s not much to say about the <em>NSJSONSerialization</em> class, except for the fact that is very simple and straightforward to be used. There are some simple rules that should follow, but further than that it takes all the hassle away from us when some JSON conversion is needed. In order to convert a JSON value into a Foundation form, it has to be a <em>NSData</em> object. The returned converted object is either an array (<em>NSArray</em>), or a dictionary (<em>NSDictionary</em>). Their contained objects however can be instances of <em>NSString</em>, <em>NSNumber</em>, <em>NSNull</em>, and of course <em>NSArray</em> and <em>NSDictionary</em>. The <em>NSJSONSerialization</em> class provides ways for checking if a JSON data is valid before doing any conversion, so you can use it in order to make sure before performing any conversion. On the other hand now, when you need to turn a Foundation object into JSON, you should have in mind that the produced object is always of <em>NSData</em> type. As you assume from what I said until now, it looks like managing JSON as a string doesn&#x2019;t seem to be an option, but that&#x2019;s not true. As you&#x2019;ll find out later in this tutorial, we can have the JSON expressed as a <em>NSString</em> object, simply by doing a small kind of trick.</p>
<p>Going to <em>NSXMLParser</em> class now, I have to say that is a very convenient one and makes the parsing of XML data a piece of cake. It&#x2019;s responsible for doing the actual parsing work, and it lets us know about each item that is found during parsing through delegate methods. It provides a great number of such methods, but that doesn&#x2019;t mean that all of them must be implemented to an app. The ones that will be selected for implementation depend on how the parsed data should be handled.</p>
<p>So, as you guess my goal in this tutorial is to teach you how to work with JSON and XML data, and how to handle it so you can use it in your applications. At this point, I should point out two facts: At first, I presume that you know what JSON and XML is, and how data is formed in both formats. If you don&#x2019;t feel very confident about any of them, then this is a good time to find and read a bit more about them. At second, even though I&#x2019;m going to show you the basics on both of them, be sure that what you&#x2019;ll learn is going to be more than enough to help you in your apps and to put you on the right track when you&#x2019;ll need to find extra support or assistance.</p>
<p>Furthermore, in this tutorial you&#x2019;ll see a couple of other interesting things too: How to easily fetch data from the web using the <em>NSURLSession</em> class, and how to use the <em>MFMailComposeViewController</em> class to present the standard mail view controller of iOS for sending e-mails. In the rest of this tutorial you will find out why and how we will use them.</p>
<p>Lastly, as always I recommend and encourage you to visit the official documentation by Apple to get more info on every topic we&#x2019;ll discuss here. Having said that, let&#x2019;s go to see an overview of the demo app that we&#x2019;ll implement in this tutorial, as we have a lot of stuff to do next.</p>
<h2>Demo App Overview</h2>
<p>While I was trying to decide where I should get JSON and XML data from for the purpose of this tutorial, I ended up to a website that could provide me with both kind of data, so I considered it as the best option. That is the <a href="http://www.geonames.org/?ref=appcoda.com">GeoNames</a> website. It contains an enormous geographical database, an API for accessing its web services, and all that for free. Personally, I think of it as the #1 source when dealing with geographical data, so we&#x2019;ll work with it. If you are not aware about it yet, then take a few minutes and pay a visit to it.</p>
<p>From this website we&#x2019;ll get two different kind of data. The first one, is detailed information about a country. Not for a specific country, but for any country we&#x2019;ll set in our app (we&#x2019;ll talk more about that in a while). The data we&#x2019;ll fetch will be in JSON format. The second, is the neighbour countries of the one we pick for getting its details, but this time the data will be in XML format. Both cases is what exactly we need for this tutorial. Examples of the JSON and XML data we&#x2019;ll get through our demo app you can find <a href="http://api.geonames.org/countryInfoJSON?username=demo&amp;country=CH&amp;ref=appcoda.com">here (country details)</a> and <a href="http://api.geonames.org/neighbours?geonameId=2658434&amp;username=demo&amp;ref=appcoda.com">here (neighbour countries)</a>.</p>
<p><img loading="lazy" decoding="async" width="313" height="587" src="http://www.appcoda.com/wp-content/uploads/2014/08/sample_gif.gif" alt="Understanding XML and JSON Parsing in iOS Programming" class="aligncenter size-full wp-image-3911"></p>
<p>Let me say a couple of things now regarding the app itself. First of all, we won&#x2019;t create a new project from scratch. Instead, you&#x2019;ll <a href="https://dl.dropboxusercontent.com/u/2857188/JSONXMLStartApp.zip?ref=appcoda.com">download a starter app</a> where I&#x2019;ve done some basic implementation. That app contains two view controllers, plus the standard iOS email view controller which we&#x2019;ll present it through code. In the first one we will display the details of a country, while in the second we will list the neighbour countries. We will use the mail view controller (<em>MFMailComposeViewController</em> class) just to make our application more complete, but no e-mail is required to be actually sent.</p>
<p>More specifically now, in the first view controller (named <em>ViewController</em>) already exists a textfield, in which you&#x2019;ll write the name of the country you want to get information for. I already have implemented the functionality of the textfield, so our work will begin by the time you want to download data after having tapped the Search button on the keyboard. Because the URL we&#x2019;ll use for downloading the data regarding the typed country requires a two-letter country code parameter and not the whole name of the country, I&#x2019;ve added to the project two text files. In the first one you&#x2019;ll find all country names, while in the second one you&#x2019;ll see the respective two-letter country code (for example, country name=ITALY, country code=IT). When tapping on the Search button, in the <em>textFieldShouldReturn:</em> delegate method of the textfield I have already added the logic for looking up the country code based on the given country. In case that no country matching to the typed one is found, then an alert view with a respective message appears. Beyond all that, there are also two more subviews in the first view controller: A label (<em>UILabel</em>) in which we&#x2019;ll display the country name and its code after having retrieved and converted the data, and a table view for showing some details regarding the country.</p>
<p>The last cell of the above table view won&#x2019;t contain any piece of information regarding the selected country, but it will be used to take us to the second view controller. Before loading it, we will pass a unique id value regarding the country, and using that id we will get the neighbour countries. The second view controller (named <em>NeighboursViewController</em>) contains just a table view which we&#x2019;ll use to list the fetched data.</p>
<p>In the first view controller the data we&#x2019;ll download will be in JSON format. Using the <em>NSJSONSerialization</em> class we&#x2019;ll convert and add it to a dictionary (<em>NSDictionary</em>) object, and also we will convert some data back to JSON that we will set as the e-mail body in the mail view controller. In the second view controller we will get the data in XML format, and using the <em>NSXMLParser</em> class of the iOS SDK we will parse them and we will add them into an array.</p>
<p>As I have already said in the beginning of the tutorial, through the next parts you will be acquainted with both classes and you&#x2019;ll see how to handle both JSON and XML data. </p>
<h2>Register an Account on GeoNames</h2>
<p>Let&#x2019;s get started by paying a visit to the <a href="http://www.geonames.org/?ref=appcoda.com">GeoNames</a> website for creating a new account. If you want to know more about that, feel free to navigate yourself around and see what it offers. A very interesting part of it, is the <a href="http://www.geonames.org/export/ws-overview.html?ref=appcoda.com">Web Services Overview</a> where you can find a list all of the provided services. By clicking on a service you can see details about it and how to use it, while you can have live examples of JSON and XML data returned to you by clicking on the respective links.</p>
<p>Anyway, after having seen the website, go and click on the <strong>Login</strong> link at the top-right side of the index page:</p>
<p><img loading="lazy" decoding="async" width="600" height="91" src="http://www.appcoda.com/wp-content/uploads/2014/08/t17_1_login_link.png" alt="Understanding XML and JSON Parsing in iOS Programming" class="aligncenter size-full wp-image-3912"></p>
<p>In the next page you&#x2019;ll find two forms, one for logging in and one for creating a new account. The second one is what we need. Fill the form in, and then click on the <strong>create account</strong> button. Make sure to remember the user name you provide, as we&#x2019;ll need it in a while.</p>
<p><img loading="lazy" decoding="async" width="498" height="295" src="http://www.appcoda.com/wp-content/uploads/2014/08/t17_2_create_account_form.png" alt="Understanding XML and JSON Parsing in iOS Programming" class="aligncenter size-full wp-image-3913"></p>
<p>A confirmation e-mail will be sent to your e-mail address. Wait a couple of minutes until you receive it, and then open it to activate your account. A page similar to the next one will open:</p>
<p><img loading="lazy" decoding="async" width="600" height="169" src="http://www.appcoda.com/wp-content/uploads/2014/08/t17_3_geonames_confirmation.png" alt="Understanding XML and JSON Parsing in iOS Programming" class="aligncenter size-full wp-image-3914"></p>
<p>There&#x2019;s one more step required before you&#x2019;re finished here. That is to enable your account for using the free web services, and in order to do that, you must login to your GeoNames account. So, log yourself in, locate the respective link and just click it. You can now log out and go straight ahead to the project.</p>
<p>In order to do any call on the GeoNames API, it&#x2019;s necessary to provide a valid username, such as the one you just created. Without it, no results will be returned when querying the GeoNames database, instead you&#x2019;ll receive just an error message back from the server. To avoid that, simply open the <em>AppDelegate.m</em> file, and at the top of it locate the next lines:</p>
<pre lang="objc">#warning Set your Geonames username in the kUsername constant.
NSString *const kUsername = @&quot;YOUR_USERNAME_HERE&quot;;
</pre>
<p>Remove or comment my custom warning that exists there, and set your username in place of the &#x201C;YOUR_USERNAME_HERE&#x201D; value. After doing so, you&#x2019;re ready to use the GeoNames services properly.</p>
<h2>A Convienient Class Method</h2>
<p>The data that will be displayed in our sample app are going to be downloaded in real time using the GeoNames web services. To perform all downloads, we&#x2019;ll use the <em>NSURLSession</em> class, which was first introduced on iOS 7 and tends to replace the <em>NSURLConnection</em> class. The downloading process is going to be repeated in two different view controllers, and it would be a really bad programming practice if we would write the same code twice. Instead, we&#x2019;ll create a small, class method, in which we&#x2019;ll add all the code needed to fetch the data we want, and we&#x2019;ll call it every time we need it. We are going to make it a class method, so we can instantly call it without initializing extra objects. I should note that I purposely didn&#x2019;t include this method in the starter app, as I believe that working with the <em>NSURLSession</em> class is a very important task, and always beneficial, even if we won&#x2019;t focus on it too much.</p>
<p>So, let&#x2019;s get started by going to the <em>AppDelegate.h</em> file first, and by declaring the method as shown below:</p>
<pre lang="objc">@interface AppDelegate : UIResponder <uiapplicationdelegate>

@property (strong, nonatomic) UIWindow *window;


+(void)downloadDataFromURL:(NSURL *)url withCompletionHandler:(void(^)(NSData *data))completionHandler;

@end
</uiapplicationdelegate></pre>
<p>There are three noticeable things here. The first one is that we begin with the plus (+) symbol instead of the minus, as this is a class method. Next, as you can see it accepts two parameters: The first one is the URL that we&#x2019;ll get the data from. The second one, is a completion handler that the method will invoke after having fetched the desired data.</p>
<p>In order to get the data we need, we&#x2019;ll use a <em>NSURLSessionDataTask</em> task. That class, which is a child of the <em>NSURLSessionTask</em> abstract class, it requires two preliminary steps before putting it in action: To instantiate a <em>NSURLSessionConfiguration</em> and a <em>NSURLSession</em> object. In that task, we&#x2019;ll provide the URL of the method&#x2019;s parameter. Also, the method we&#x2019;ll use has a completion handler block which is called after the data has been downloaded or if any error has occurred. In there we&#x2019;ll handle the error if exists (we&#x2019;ll simply log it to the console), and we&#x2019;ll also show the HTTP status code if is other than 200 (meaning that something went wrong). In any case though, we&#x2019;ll invoke the completion handler of the parameter, and we&#x2019;ll pass the returned data as a <em>NSData</em> object. Let&#x2019;s see all that in code now, in the <em>AppDelegate.m</em> file:</p>
<pre lang="objc">+(void)downloadDataFromURL:(NSURL *)url withCompletionHandler:(void (^)(NSData *))completionHandler{
    // Instantiate a session configuration object.
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    // Instantiate a session object.
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];

    // Create a data task object to perform the data downloading.
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        if (error != nil) {
            // If any error occurs then just display its description on the console.
            NSLog(@&quot;%@&quot;, [error localizedDescription]);
        }
        else{
            // If no error occurs, check the HTTP status code.
            NSInteger HTTPStatusCode = [(NSHTTPURLResponse *)response statusCode];

            // If it&apos;s other than 200, then show it on the console.
            if (HTTPStatusCode != 200) {
                NSLog(@&quot;HTTP status code = %d&quot;, HTTPStatusCode);
            }

            // Call the completion handler with the returned data on the main thread.
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                completionHandler(data);
            }];
        }
    }];

    // Resume the task.
    [task resume];
}
</pre>
<p>Even though everything is quite easy to be understood, and the comments help even more on that, I would just like to underline the use of the next couple of lines:</p>
<pre lang="objc">[[NSOperationQueue mainQueue] addOperationWithBlock:^{
                completionHandler(data);
            }];
</pre>
<p>The <em>task</em> runs asynchronously in a background thread, but it&#x2019;s necessary to call our completion handler on the main thread of the app and not on the thread of the task, so as we ensure that any visual updates after having fetched the data will occur on the proper time. Therefore, we add the completion handler call as an operation to the main thread, using the <em>NSOperationQueue</em> class. If you&#x2019;re curious about what could happen if we wouldn&#x2019;t use that operation block, then try to make the completion handler call out of that block after we have the app implemented. You&#x2019;ll find out that the interface doesn&#x2019;t get updated properly, and unpredictable delays in the app execution occur.</p>
<p>Finally, notice that we use this command:</p>
<pre lang="objc">[task resume];
</pre>
<p>for making the task start working.</p>
<p>Now that we have this useful method ready, we can see how we can handle JSON data and convert it to a manageable form.</p>
<h2>Downloading a Country&#x2019;s Info as JSON Data</h2>
<p>In this part we are going to do one of the most important tasks in this tutorial: We are going to download the data for a country of which the name we type in the textfield of on the <em>ViewController</em> view controller, and then we are going to convert the returned JSON from a <em>NSData</em> object into to a <em>NSDictionary</em> object.</p>
<p>We&#x2019;ll see everything in details, but first, let&#x2019;s declare a private method in the <em>ViewController.m</em> file. Go to the private class section and add the next line:</p>
<pre lang="objc">@interface ViewController ()

...

-(void)getCountryInfo;

@end
</pre>
<p>Before its implementation, let&#x2019;s call it. The point that we should do that, is right after the user has tapped on the Search button of the keyboard, and the two-letter country representation has been found. So, go to the <em>textFieldShouldReturn:</em> delegate method, and locate the next line:</p>
<pre lang="objc">self.countryCode = [self.arrCountryCodes objectAtIndex:index];
</pre>
<p>Then, right below it, add the method call:</p>
<pre lang="objc">[self getCountryInfo];
</pre>
<p>The <em>if</em> clause that contains the first line should now look like this:</p>
<pre lang="objc">if (index != -1) {
        // Get the two-letter country code from the arrCountryCodes array.
        self.countryCode = [self.arrCountryCodes objectAtIndex:index];

        // Download the country info.
        [self getCountryInfo];
    }
</pre>
<p>Now, let&#x2019;s move ahead to the implementation of the <em>getCountryInfo</em> method. At first, we must specify the URL that we&#x2019;ll get the data from. The URL is this:</p>
<pre lang="objc">http://api.geonames.org/countryInfoJSON
</pre>
<p>and we&#x2019;re going to use it for making a GET request. We must provide two parameter values in the above URL, the username of the GeoNames services, and the country we want to look up info for, expressed as a two-letter string (for that we&#x2019;ll use the <em>countryCode</em> property already existed in the <em>ViewController</em> class). Let&#x2019;s see that:</p>
<pre lang="objc">-(void)getCountryInfo{
    // Prepare the URL that we&apos;ll get the country info data from.
    NSString *URLString = [NSString stringWithFormat:@&quot;http://api.geonames.org/countryInfoJSON?username=%@&amp;country=%@&quot;, kUsername, self.countryCode];
    NSURL *url = [NSURL URLWithString:URLString];


}
</pre>
<p>If you <em>NSLog</em> the above <em>URLString</em> value now, you&#x2019;ll see something like this:</p>
<pre lang="objc">http://api.geonames.org/countryInfoJSON?username=XXXXXXXX&amp;country=GR
</pre>
<p>(Where XXXXXXXX is your username)</p>
<p>Now, we can call the <em>downloadDataFromURL:withCompletionHandler:</em> class method we previously implemented. In this, we&#x2019;ll provide the URL we formed in the above code snippet, and we&#x2019;ll implement the completion handler block:</p>
<pre lang="objc">-(void)getCountryInfo{
    ...

    [AppDelegate downloadDataFromURL:url withCompletionHandler:^(NSData *data) {
        // Check if any data returned.
        if (data != nil) {

        }
    }];

}
</pre>
<p>Notice that is always necessary to check if the returned data is other than nil. In case of error, no data will exist and the <em>data</em> object will be nil, so be careful.</p>
<p>For first time, we are about to use the <em>NSJSONSerialization</em> class in order to convert the fetched JSON data into a Foundation object, so we can handle it. Usually, a JSON converted object matches either to a <em>NSArray</em> object, or to a <em>NSDictionary</em> object. In the most cases you can know and tell what object the JSON will be converted to, as in almost every app you can find out the form of the JSON data you&#x2019;ll fetch. In the rare cases you don&#x2019;t know how the JSON data is formed and what Foundation object to expect after the conversion, see right next how to determine this.</p>
<p>Before I show you how to find out the class of the converted JSON, let me introduce the method that does all the magical work. That is the <em>JSONObjectWithData:options:error:</em>. The first parameter of that method, is the <em>NSData</em> data downloaded from the web. What this method returns, is an <em>id</em> Foundation type.</p>
<p>Returning to what I was saying before and using this method, simply by writing this (in any app):</p>
<pre lang="objc">NSLog(@&quot;%@&quot;, [[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&amp;error] class]);
</pre>
<p>you can see in the console the actual class of the converted JSON data. In our case, if we run the app using the above <em>NSLog</em> command, we&#x2019;ll see the following:</p>
<pre lang="objc">__NSCFDictionary
</pre>
<p>That means that by converting the returned JSON data we&#x2019;ll get a <em>NSDictionary</em> object. That&#x2019;s great and really interesting!</p>
<p>There&#x2019;s one more way to determine the kind of the returned data. We can open a browser (Safari, Chrome or anything else you use), and set the URL in the address line:</p>
<p><img loading="lazy" decoding="async" width="551" height="59" src="http://www.appcoda.com/wp-content/uploads/2014/08/t17_4_safari_url.png" alt="Understanding XML and JSON Parsing in iOS Programming" class="aligncenter size-full wp-image-3915"></p>
<p>By pressing the Return key, you&#x2019;ll see the JSON string right in front of you:</p>
<p><img loading="lazy" decoding="async" width="600" height="65" src="http://www.appcoda.com/wp-content/uploads/2014/08/t17_5_safari_json.png" alt="Understanding XML and JSON Parsing in iOS Programming" class="aligncenter size-full wp-image-3916"></p>
<p>The above screenshot might not be so clear, therefore I&#x2019;m copying-pasting the returned JSON here as well:</p>
<pre lang="objc">{&quot;geonames&quot;:[{&quot;continent&quot;:&quot;EU&quot;,&quot;capital&quot;:&quot;Athens&quot;,&quot;languages&quot;:&quot;el-GR,en,fr&quot;,&quot;geonameId&quot;:390903,&quot;south&quot;:34.8020663391466,&quot;isoAlpha3&quot;:&quot;GRC&quot;,&quot;north&quot;:41.7484999849641,&quot;fipsCode&quot;:&quot;GR&quot;,&quot;population&quot;:&quot;11000000&quot;,&quot;east&quot;:28.2470831714347,&quot;isoNumeric&quot;:&quot;300&quot;,&quot;areaInSqKm&quot;:&quot;131940.0&quot;,&quot;countryCode&quot;:&quot;GR&quot;,&quot;west&quot;:19.3736035624134,&quot;countryName&quot;:&quot;Greece&quot;,&quot;continentName&quot;:&quot;Europe&quot;,&quot;currencyCode&quot;:&quot;EUR&quot;}]}
</pre>
<p>The initial curly brace ({) indicates a dictionary object. The bracket ([) indicates an array. Next, there&#x2019;s another curly brace, meaning another dictionary. In simple words, the above JSON says: We have a dictionary, in which there&#x2019;s an array with one object only, and that object is another dictionary containing all the data we want (dictionary &gt; array &gt; dictionary).</p>
<p>So, what we have to do is this: First, we&#x2019;ll convert the returned JSON data into a <em>NSDictionary</em> object. Then, we will check if any error has occurred during conversion, and if not we&#x2019;ll extract the array from that dictionary using the key <em>geonames</em>. Finally, we&#x2019;ll extract the second, desired dictionary from the first index of that array. Speaking in code this time, here&#x2019;s what I just said:</p>
<pre lang="objc">-(void)getCountryInfo{
    ...

    [AppDelegate downloadDataFromURL:url withCompletionHandler:^(NSData *data) {
        // Check if any data returned.
        if (data != nil) {
            // Convert the returned data into a dictionary.
            NSError *error;
            NSMutableDictionary *returnedDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&amp;error];

            if (error != nil) {
                NSLog(@&quot;%@&quot;, [error localizedDescription]);
            }
            else{
                self.countryDetailsDictionary = [[returnedDict objectForKey:@&quot;geonames&quot;] objectAtIndex:0];
            }
        }
    }];

}
</pre>
<p>Initially, we convert the JSON data to the <em>returnedDict</em> dictionary. Next, we get the array and the dictionary of the first index of that array, and we assign it to the <em>countryDetailsDictionary</em> property. Regarding the <em>error</em> object in the above implementation, it&#x2019;s our duty to check if it&#x2019;s nil or not, and to take the proper actions. For the sake of the simplicity, we just log the description of the error, if any occurs of course.</p>
<p>For now, it would be nice if we could see the fetched data even on the console, therefore complete the above method as shown right next:</p>
<pre lang="objc">-(void)getCountryInfo{
    ...

    [AppDelegate downloadDataFromURL:url withCompletionHandler:^(NSData *data) {
        // Check if any data returned.
        if (data != nil) {
            // Convert the returned data into a dictionary.
            NSError *error;
            NSMutableDictionary *returnedDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&amp;error];

            if (error != nil) {
                NSLog(@&quot;%@&quot;, [error localizedDescription]);
            }
            else{
                self.countryDetailsDictionary = [[returnedDict objectForKey:@&quot;geonames&quot;] objectAtIndex:0];
                NSLog(@&quot;%@&quot;, self.countryDetailsDictionary);
            }
        }
    }];

}
</pre>
<p>Running the app now, will return something like the next output:</p>
<p><img loading="lazy" decoding="async" width="381" height="308" src="http://www.appcoda.com/wp-content/uploads/2014/08/t17_6_country_info.png" alt="Understanding XML and JSON Parsing in iOS Programming" class="aligncenter size-full wp-image-3917" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t17_6_country_info.png 381w, https://www.appcoda.com/content/images/wordpress/2014/08/t17_6_country_info-371x300.png 371w" sizes="(max-width: 381px) 100vw, 381px"></p>
<pre lang="objc">{
    areaInSqKm = &quot;131940.0&quot;;
    capital = Athens;
    continent = EU;
    continentName = Europe;
    countryCode = GR;
    countryName = Greece;
    currencyCode = EUR;
    east = &quot;28.2470831714347&quot;;
    fipsCode = GR;
    geonameId = 390903;
    isoAlpha3 = GRC;
    isoNumeric = 300;
    languages = &quot;el-GR,en,fr&quot;;
    north = &quot;41.7484999849641&quot;;
    population = 11000000;
    south = &quot;34.8020663391466&quot;;
    west = &quot;19.3736035624134&quot;;
}
</pre>
<p>So, we&#x2019;ve successfully managed to download JSON data and to convert it to a NSDictionary object. That was a very important job, but we have more to do. Next, we&#x2019;ll display all that data.</p>
<h2>Populating the Converted JSON Data</h2>
<p>Now that we have the data we want on our hands, it&#x2019;s time to display it. There are two subviews for showing data: A label for the country title along with its two-letter code, and a table view for the rest of it. As you see, there&#x2019;s a lot of data that is being returned, but we are not going to use all of it. Actually, we will show only the following (besides the country name):</p>
<ul>
<li>Capital</li>
<li>Continent</li>
<li>Population</li>
<li>Area in Square Km</li>
<li>Currency</li>
<li>Languages</li>
</ul>
<p>Let&#x2019;s get started by the easy one, the country name. While being in the <em>getCountryInfo</em> method and in the <em>else</em> case, add the next line to display the country name to the label existing right below the textfield:</p>
<pre lang="objc">// Set the country name to the respective label.
                self.lblCountry.text = [NSString stringWithFormat:@&quot;%@ (%@)&quot;, [self.countryDetailsDictionary objectForKey:@&quot;countryName&quot;], [self.countryDetailsDictionary objectForKey:@&quot;countryCode&quot;]];
</pre>
<p>This will display something like: <strong>ITALY (IT)</strong>.</p>
<p>In the same <em>else</em> case, add the next two lines as well, in order to reload the data in the table view and make it appear (initially the table view is hidden):</p>
<pre lang="objc">// Reload the table view.
                [self.tblCountryDetails reloadData];

                // Show the table view.
                self.tblCountryDetails.hidden = NO;
</pre>
<p>After the above couple of modifications, your else case in the completion handler block should look like this:</p>
<pre lang="objc"> else{
                // Set the country name to the respective label.
                self.lblCountry.text = [NSString stringWithFormat:@&quot;%@ (%@)&quot;, [self.countryDetailsDictionary objectForKey:@&quot;countryName&quot;], [self.countryDetailsDictionary objectForKey:@&quot;countryCode&quot;]];

                // Reload the table view.
                [self.tblCountryDetails reloadData];

                // Show the table view.
                self.tblCountryDetails.hidden = NO;
            }
</pre>
<p>Our work in this method is over, so let&#x2019;s focus on the table view. Initially, go to the <em>tableView:numberOfRowsInSection:</em> and change the <em>return 0;</em> command to this:</p>
<pre lang="objc">-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 7;
}
</pre>
<p>We want 7 rows to exist in our table view. We&#x2019;ll use the first six rows to display the data I mentioned above, and in the last row we&#x2019;ll have a cell that will let us get navigated into a new view controller, where we&#x2019;ll get the neighbour countries of the selected one.</p>
<p>Next, we&#x2019;ll work in the <em>tableView:cellForRowAtIndexPath:</em> method. As you see, there&#x2019;s the following initial implementation, where the cell is dequeued or created if it does not exist:</p>
<pre lang="objc">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@&quot;cell&quot;];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@&quot;Cell&quot;];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    return cell;
}
</pre>
<p>Notice that both the accessory type and the selection style are set to None for all cells.</p>
<p>Our work here is quite easy. We&#x2019;ll use a <em>switch</em> statement, in which we will check the index of each row. Depending on this value, we will extract the proper data from the <em>countryDetailsDictionary</em> dictionary and we&#x2019;ll assign it to the cell&#x2019;s text label. At the same time, we&#x2019;ll add a short descriptive text as a subtitle on each cell. Let&#x2019;s see it:</p>
<pre lang="objc">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@&quot;cell&quot;];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@&quot;Cell&quot;];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    switch (indexPath.row) {
        case 0:
            cell.detailTextLabel.text = @&quot;Capital&quot;;
            cell.textLabel.text = [self.countryDetailsDictionary objectForKey:@&quot;capital&quot;];
            break;
        case 1:
            cell.detailTextLabel.text = @&quot;Continent&quot;;
            cell.textLabel.text = [self.countryDetailsDictionary objectForKey:@&quot;continentName&quot;];
            break;
        case 2:
            cell.detailTextLabel.text = @&quot;Population&quot;;
            cell.textLabel.text = [self.countryDetailsDictionary objectForKey:@&quot;population&quot;];
            break;
        case 3:
            cell.detailTextLabel.text = @&quot;Area in Square Km&quot;;
            cell.textLabel.text = [self.countryDetailsDictionary objectForKey:@&quot;areaInSqKm&quot;];
            break;
        case 4:
            cell.detailTextLabel.text = @&quot;Currency&quot;;
            cell.textLabel.text = [self.countryDetailsDictionary objectForKey:@&quot;currencyCode&quot;];
            break;
        case 5:
            cell.detailTextLabel.text = @&quot;Languages&quot;;
            cell.textLabel.text = [self.countryDetailsDictionary objectForKey:@&quot;languages&quot;];
            break;
        case 6:
            cell.textLabel.text = @&quot;Neighbour Countries&quot;;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleDefault;
            break;

        default:
            break;
    }

    return cell;
}
</pre>
<p>Pay special attention to the last case, where we add the cell that will take us to the neighbour countries list. For this cell only, we set the disclosure indicator as the accessory type and the default selection style. That&#x2019;s because we want it to prompt us to tap it, and to be highlighted when is tapped.</p>
<p>Now you can run the app and see it functioning properly for the first time. Type a country&#x2019;s name in the text field, and wait until you see its details on the table view. Always remember that these details are fetched in real time from a web server as JSON data, and our app is the one that makes it possible to view that data!</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/08/t17_7_sample_country_info.png" alt="Understanding XML and JSON Parsing in iOS Programming" class="aligncenter size-full wp-image-3918" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t17_7_sample_country_info.png 247w, https://www.appcoda.com/content/images/wordpress/2014/08/t17_7_sample_country_info-164x300.png 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<h2>Creating a JSON</h2>
<p>Further than just converting JSON data into a Foundation object (NSArray, NSDictionary), the <em>NSJSONSerialization</em> class can also help us convert data stored in Foundation objects to JSON format. In the previous sections we managed to implement the first case and make our app work great. Now, we will see how to produce JSON data.</p>
<p>If you look closely in the view controller when running the app, there is a <em>Compose</em> bar button item at the right side of the navigation bar:</p>
<p><img loading="lazy" decoding="async" width="480" height="248" src="http://www.appcoda.com/wp-content/uploads/2014/08/t17_8_navigation_compose.png" alt="Understanding XML and JSON Parsing in iOS Programming" class="aligncenter size-full wp-image-3919"></p>
<p>Using this button we will perform two things: The first one is to create a JSON string using the <em>NSJSONSerialization</em> class. This string will contain just the country data displayed on our view controller, excluding all the data that we don&#x2019;t use. The second is to send that string via e-mail, so we&#x2019;ll make the standard iOS mail view controller appear.</p>
<p>Our work will take place in the <em>sendJSON:</em> IBAction method. We&#x2019;ll begin by creating a new dictionary (NSDictionary) that will contain only the values we want:</p>
<pre lang="objc">- (IBAction)sendJSON:(id)sender {
    // Create a dictionary containing only the values we care about.
    NSDictionary *dictionary = @{@&quot;countryName&quot;: [self.countryDetailsDictionary objectForKey:@&quot;countryName&quot;],
                                 @&quot;countryCode&quot;: [self.countryDetailsDictionary objectForKey:@&quot;countryCode&quot;],
                                 @&quot;capital&quot;: [self.countryDetailsDictionary objectForKey:@&quot;capital&quot;],
                                 @&quot;continent&quot;: [self.countryDetailsDictionary objectForKey:@&quot;continentName&quot;],
                                 @&quot;population&quot;: [self.countryDetailsDictionary objectForKey:@&quot;population&quot;],
                                 @&quot;areaInSqKm&quot;: [self.countryDetailsDictionary objectForKey:@&quot;areaInSqKm&quot;],
                                 @&quot;currency&quot;: [self.countryDetailsDictionary objectForKey:@&quot;currencyCode&quot;],
                                 @&quot;languages&quot;: [self.countryDetailsDictionary objectForKey:@&quot;languages&quot;]
                                 };

}
</pre>
<p>Now the most important part: We&#x2019;ll convert that dictionary into JSON data. That&#x2019;s just a matter of one line:</p>
<pre lang="objc">- (IBAction)sendJSON:(id)sender {
    ...

    // Convert the dictionary into a JSON data object.
    NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];

}
</pre>
<p>The above does all the magical work. However, we have a problem here: The converted object is a <em>NSData</em> object, and if you try to display its contents you&#x2019;ll get something like that:</p>
<pre lang="objc"><7b0a2020 20224174 20224575 20226361 20226375 22475222 22617265 30303022 31303030 31333139 47726565 63792220 65732220 67756167 70697461 22636f75 6e747279 436f6465 22203a20 2c0a2020 226c616e 3a202265 6c2d4752 2c656e2c 6672222c 0a202022 636f756e 7472794e 616d6522 203a2022 6365222c 636f6e74 696e656e 7422203a 726f7065 222c0a20 7272656e 3a202245 5552222c 706f7075 6c617469 6f6e2220 3a202231 61496e53 714b6d22 34302e30 6c22203a 68656e73 220a7d>
</7b0a2020></pre>
<p>Of course, this is not readable by humans, so how can we show and send the actual JSON string? Well, we&#x2019;ll do a small trick, which is shown below:</p>
<pre lang="objc">- (IBAction)sendJSON:(id)sender {
    ...

    // Convert the JSON data into a string.
    NSString *JSONString = [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding];

}
</pre>
<p>As you see, we simply convert the <em>NSData</em> object into a <em>NSString</em> object using the above way. This is safe to do, as we already know that a JSON value is a string value. If we use a <em>NSLog</em> command at this point, here&#x2019;s what we&#x2019;ll see on the console:</p>
<pre lang="objc">{
  &quot;countryCode&quot; : &quot;GR&quot;,
  &quot;languages&quot; : &quot;el-GR,en,fr&quot;,
  &quot;countryName&quot; : &quot;Greece&quot;,
  &quot;continent&quot; : &quot;Europe&quot;,
  &quot;currency&quot; : &quot;EUR&quot;,
  &quot;population&quot; : &quot;11000000&quot;,
  &quot;areaInSqKm&quot; : &quot;131940.0&quot;,
  &quot;capital&quot; : &quot;Athens&quot;
}
</pre>
<p>That&#x2019;s great! It&#x2019;s what exactly we want, and by seeing this we can be sure that our dictionary was successfully converted into a JSON string. Now, let&#x2019;s make our example more complete, by making it capable of sending the above JSON string via e-mail. To make our work easier, I&#x2019;ve already imported the necessary library (<em>MFMailComposeViewController</em>), and have adopted the respective protocol (<em>MFMailComposeViewControllerDelegate</em>) regarding the e-mail view controller, so we just need to present it here.</p>
<p>One basic thing you should always have in mind when using the <em>MFMailComposeViewController</em> class for displaying the e-mail view controller, is that you should check if the device can actually send e-mails. We&#x2019;ll perform that check here, and then we&#x2019;ll do these:</p>
<ol>
<li>We&#x2019;ll initialize a <em>MFMailComposeViewController</em> object and we&#x2019;ll make the <em>ViewController</em> class its delegate.</li>
<li>We&#x2019;ll set the subject of the e-mail.</li>
<li>We&#x2019;ll set the body of the e-mail, which obviously is the JSON string we earlier produced.</li>
<li>We&#x2019;ll present the view controller.</li>
</ol>
<p>Let&#x2019;s see all that:</p>
<pre lang="objc">- (IBAction)sendJSON:(id)sender {
    ...

    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
        mailViewController.mailComposeDelegate = self;

        [mailViewController setSubject:@&quot;Country JSON&quot;];

        [mailViewController setMessageBody:JSONString isHTML:NO];

        [self presentViewController:mailViewController animated:YES completion:nil];
    }
}
</pre>
<p>The IBAction method is now ready. Notice that the <em>mailComposeController:didFinishWithResult:error:</em> delegate method of the * MFMailComposeViewControllerDelegate* protocol has already been implemented, so no more action is required from us.</p>
<p>Go and test the app once again. You&#x2019;ll find out that the mail view controller is appeared (modally), and the JSON string is automatically set as the body of the e-mail.</p>
<p><img loading="lazy" decoding="async" width="222" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/08/t17_9_sample_email.png" alt="Understanding XML and JSON Parsing in iOS Programming" class="aligncenter size-full wp-image-3920" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t17_9_sample_email.png 222w, https://www.appcoda.com/content/images/wordpress/2014/08/t17_9_sample_email-164x300.png 164w" sizes="(max-width: 222px) 100vw, 222px"></p>
<h2>Downloading the Neighbour Countries</h2>
<p>As you have seen up to here, handling JSON data is really easy with the <em>NSJSONSerialization</em> class. Now, it&#x2019;s time to move to the second part of the app, where we&#x2019;ll download data regarding the neighbour countries of the selected one, but this time it&#x2019;s going to be in XML format. Through the next sections you&#x2019;ll see how you can use the <em>NSXMLParser</em> class for parsing XML data, and you&#x2019;ll find out how easy it is to end up with the needed logic for extracting the data.</p>
<p>In order to download the neighbours of the selected country, it&#x2019;s necessary to provide to the URL that we&#x2019;ll call a unique value regarding the country, named <em>geonameId</em>. That value was returned along with the rest of the data, and if you look closely to the dictionary contents we previously logged in the debugger, you&#x2019;ll find it there. So, first of all, we must make the <em>ViewController</em> class send the <em>geonameId</em> value to the <em>NeighboursViewController</em>, and then proceed to the rest of the work. Open the <em>NeighboursViewController.h</em> and declare the following property:</p>
<pre lang="objc">@interface NeighboursViewController : UIViewController <uitableviewdelegate, uitableviewdatasource, nsxmlparserdelegate>

...

@property (nonatomic, strong) NSString *geonameID;

@end
</uitableviewdelegate,></pre>
<p>As you assume, in this property we&#x2019;ll pass the value we want. Now, back to the <em>ViewController.m</em> file, go to the <em>prepareForSegue:sender:</em> method. This one is called before the new view controller actually gets loaded, so it&#x2019;s the best place to set the <em>geonameId</em> value to the <em>geonameID</em> property. Add the next code segment:</p>
<pre lang="objc">-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.identifier isEqualToString:@&quot;idSegueNeighbours&quot;]) {
        NeighboursViewController *neighboursViewController = [segue destinationViewController];
        neighboursViewController.geonameID = [self.countryDetailsDictionary objectForKey:@&quot;geonameId&quot;];        
    }
}
</pre>
<p>Having this property set, we are able to proceed to our work. Let&#x2019;s continue by downloading the neighbour countries data, as we previously did with the country&#x2019;s details data. Go to the <em>NeighboursViewController.m</em> file, in the private class section, and declare the next method:</p>
<pre lang="objc">@interface NeighboursViewController ()

-(void)downloadNeighbourCountries;

@end
</pre>
<p>We want the neighbour countries data to be downloaded when the view controller gets loaded, so go to the <em>viewDidLoad</em> method and call it:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    // Download the neighbour countries data.
    [self downloadNeighbourCountries];
}
</pre>
<p>Now, let&#x2019;s see its implementation. The first thing we have to do is to specify the URL that we&#x2019;ll get the data from. Once we have it formed, we&#x2019;ll call the <em>downloadDataFromURL:withCompletionHandler:</em> class method to perform the actual download. Let&#x2019;s see everything up to this point:</p>
<pre lang="objc">-(void)downloadNeighbourCountries{
    // Prepare the URL that we&apos;ll get the neighbour countries from.
    NSString *URLString = [NSString stringWithFormat:@&quot;http://api.geonames.org/neighbours?geonameId=%@&amp;username=%@&quot;, self.geonameID, kUsername];

    NSURL *url = [NSURL URLWithString:URLString];

    // Download the data.
    [AppDelegate downloadDataFromURL:url withCompletionHandler:^(NSData *data) {
        // Make sure that there is data.
        if (data != nil) {

        }
    }];
}
</pre>
<p>Simple as that! In the next part we are going to begin parsing the data in the above <em>if</em> clause, and we&#x2019;ll implement all the necessary delegate methods of the parser that will help us to extract the exact data we need.</p>
<h2>Parsing the XML Data</h2>
<p>In order to parse an XML file or XML data in general, iOS SDK provides the <em>NSXMLParser</em> class. This one performs all the hard work on the background by going through all the data (by parsing them), and it provides us with some really useful delegate methods. Using them, we can have full control over parsing and handle any data found, in any way we want. In this example, we&#x2019;ll use some of those delegate methods, and we&#x2019;ll add all the data we are interested in to an array.</p>
<p>Being more specific, let me introduce you the delegate methods of the <em>NSXMLParser</em> class we&#x2019;ll use, and what each of them is for. For clarification reasons only, I need to say that every XML data that&#x2019;s about to be parsed, is considered as an XML document by iOS. Keep that in mind when reading next.</p>
<p>The delegate methods now:</p>
<ol>
<li><em>parserDidStartDocument:</em> This one is called when the parsing actually starts. It&#x2019;s obvious that is called just once per XML document.</li>
<li><em>parserDidEndDocument:</em> This one is the complement of the first one, and is called when the parser reaches the end of the XML data.</li>
<li><em>parser:parseErrorOccurred:</em> This delegate method is called when an error occurs during the parsing. The method contains an error object, which you can use to define the actual error.</li>
<li><em>parser:didStartElement:namespaceURI:qualifiedName:attributes:</em> This one is called when the opening tag of an element is found.</li>
<li><em>parser:didEndElement:namespaceURI:qName:</em> On the contrary to the above method, this is called when the closing tag of an element is found.</li>
<li><em>parser:foundCharacters:</em> This method is called during the parsing of the contents of an element. Its second argument is a string value containing the character that was just parsed.</li>
</ol>
<p>Now that you know the delegate methods we&#x2019;re about to use in our sample app, let&#x2019;s discuss a bit about the logic that we&#x2019;ll follow. Well, as it&#x2019;s quite possible that multiple results will be returned after a call on the GeoNames API, it&#x2019;s obvious that we&#x2019;ll have to insert the parsed data into an array. But, what exactly are we going to add to this array?</p>
<p>To answer the above question, we just have to pay a visit to the GeoNames website and perform an API call using the browser, so we see what is being returned when asking for neighbour countries. There&#x2019;s no simpler option than using the example <a href="http://api.geonames.org/neighbours?geonameId=2658434&amp;username=demo&amp;ref=appcoda.com">link</a> of the website, which takes us to a page with the following results:</p>
<p><img loading="lazy" decoding="async" width="569" height="467" src="http://www.appcoda.com/wp-content/uploads/2014/08/t17_10_neighbours_example.png" alt="Understanding XML and JSON Parsing in iOS Programming" class="aligncenter size-full wp-image-3921" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t17_10_neighbours_example.png 569w, https://www.appcoda.com/content/images/wordpress/2014/08/t17_10_neighbours_example-365x300.png 365w" sizes="(max-width: 569px) 100vw, 569px"></p>
<p>Among all the values that been returned, we are going to use just two of them in our app: The <em>toponymName</em> and the <em>name</em> of the neighbour country.</p>
<p>With that in mind, we could say that for every neighbour country that will be parsed, we could add the above two values into a <em>dictionary</em>, and then add each dictionary to the array. In order to make this general idea more specific, let me say what we&#x2019;ll do in each delegate method, in the order they were previously presented:</p>
<ol>
<li><em>parserDidStartDocument:</em> In this one we&#x2019;ll initialize the array that will contain all the data regarding the neighbour countries.</li>
<li><em>parserDidEndDocument:</em> As this method signals the end of the parsing, we&#x2019;ll simply reload the table view, and we will display our data.</li>
<li><em>parser:parseErrorOccurred:</em> This is just a sample app, so we won&#x2019;t handle the error, we&#x2019;ll only log it on the console.</li>
<li><em>parser:didStartElement:namespaceURI:qualifiedName:attributes:</em> A quite important method, as we will initialize the dictionary in which we&#x2019;ll store the toponym and the country name when the element is equal to the &#x201C;<geoname>&#x201D; value. Moreover, we&#x2019;ll assign the name of the current element to a property, as we&#x2019;ll need to know it when parsing characters.</geoname></li>
<li><em>parser:didEndElement:namespaceURI:qName:</em> When the closing &#x201C;&#x201D; tag is found, the dictionary containing the two values of interest will be added to the array. Besides that, when parsing either the &#x201C;&#x201D; or the &#x201C;&#x201D; closing tags, the respective found values will be added to the dictionary.</li>
<li><em>parser:foundCharacters:</em> When the current element is equal to &#x201C;<toponymname>&#x201D; or to &#x201C;<name>&#x201D; then we&#x2019;ll store the found characters into a mutable string. The value of that string is the one we&#x2019;ll add to the dictionary when the closing tag of the respective element is parsed.</name></toponymname></li>
</ol>
<p>Enough with theory though, let&#x2019;s start writing some code. At the private section of the class, add the following properties:</p>
<pre lang="objc">@interface NeighboursViewController ()

...

@property (nonatomic, strong) NSXMLParser *xmlParser;

@property (nonatomic, strong) NSMutableArray *arrNeighboursData;

@property (nonatomic, strong) NSMutableDictionary *dictTempDataStorage;

@property (nonatomic, strong) NSMutableString *foundValue;

@property (nonatomic, strong) NSString *currentElement;


@end
</pre>
<ul>
<li>The <em>xmlParser</em> property is the one that we&#x2019;ll use to parse the XML data.</li>
<li>The <em>arrNeighboursData</em> property is the array that will contain all of the desired data after the parsing has finished.</li>
<li>The <em>dictTempDataStorage</em> property is the dictionary in which we&#x2019;ll temporarily store the two values we seek for each neighbour country until we add it to the array.</li>
<li>The <em>foundValue</em> mutable string will be used to store the found characters of the elements of interest.</li>
<li>The <em>currentElement</em> string will be assigned with the name of the element that is parsed at any moment.</li>
</ul>
<p>Now, go to the <em>downloadNeighbourCountries</em> method, and add the code shown below in the completion handler block:</p>
<pre lang="objc">-(void)downloadNeighbourCountries{
    // Prepare the URL that we&apos;ll get the neighbour countries from.
    NSString *URLString = [NSString stringWithFormat:@&quot;http://api.geonames.org/neighbours?geonameId=%@&amp;username=%@&quot;, self.geonameID, kUsername];

    NSURL *url = [NSURL URLWithString:URLString];

    // Download the data.
    [AppDelegate downloadDataFromURL:url withCompletionHandler:^(NSData *data) {
        // Make sure that there is data.
        if (data != nil) {
            self.xmlParser = [[NSXMLParser alloc] initWithData:data];
            self.xmlParser.delegate = self;

            // Initialize the mutable string that we&apos;ll use during parsing.
            self.foundValue = [[NSMutableString alloc] init];

            // Start parsing.
            [self.xmlParser parse];
        }
    }];
}
</pre>
<p>With these four lines in the block, we initialize the parser object, we set our class as its delegate, we initialize the mutable string that we&#x2019;ll use for storing the parsed values and finally we start parsing. Note that I have already adopted a required protocol, the <em>NSXMLParserDelegate</em>.</p>
<p>Let&#x2019;s start working on the delegate methods now, and let&#x2019;s see them in the order the were presented above. The first one:</p>
<pre lang="objc">-(void)parserDidStartDocument:(NSXMLParser *)parser{
    // Initialize the neighbours data array.
    self.arrNeighboursData = [[NSMutableArray alloc] init];
}
</pre>
<p>As I have already said, this delegate method signals the beginning of the parsing, so we initialize our array. The next one:</p>
<pre lang="objc">-(void)parserDidEndDocument:(NSXMLParser *)parser{
    // When the parsing has been finished then simply reload the table view.
    [self.tblNeighbours reloadData];
}
</pre>
<p>After the parsing has finished, we simply reload the data on the table view. For the time being nothing happens, but we&#x2019;ll work on that at the next section. Next:</p>
<pre lang="objc">-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
    NSLog(@&quot;%@&quot;, [parseError localizedDescription]);
}
</pre>
<p>Nothing difficult here too, as we simply display the error description on the console.</p>
<pre lang="objc">-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{

    // If the current element name is equal to &quot;geoname&quot; then initialize the temporary dictionary.
    if ([elementName isEqualToString:@&quot;geoname&quot;]) {
        self.dictTempDataStorage = [[NSMutableDictionary alloc] init];
    }

    // Keep the current element.
    self.currentElement = elementName;
}
</pre>
<p>Two things happen here: If the parser is about to start parsing the data of a new country, then we initialize the dictionary. The second is that we store the current element name (you&#x2019;ll see why in the last delegate method).</p>
<pre lang="objc">-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

    if ([elementName isEqualToString:@&quot;geoname&quot;]) {
        // If the closing element equals to &quot;geoname&quot; then the all the data of a neighbour country has been parsed and the dictionary should be added to the neighbours data array.
        [self.arrNeighboursData addObject:[[NSDictionary alloc] initWithDictionary:self.dictTempDataStorage]];
    }
    else if ([elementName isEqualToString:@&quot;name&quot;]){
        // If the country name element was found then store it.
        [self.dictTempDataStorage setObject:[NSString stringWithString:self.foundValue] forKey:@&quot;name&quot;];
    }
    else if ([elementName isEqualToString:@&quot;toponymName&quot;]){
        // If the toponym name element was found then store it.
        [self.dictTempDataStorage setObject:[NSString stringWithString:self.foundValue] forKey:@&quot;toponymName&quot;];
    }

    // Clear the mutable string.
    [self.foundValue setString:@&quot;&quot;];
}
</pre>
<p>This delegate method is called when the closing tag of an element has been parsed. If the element is equal to the &#x201C;geoname&#x201D; value, then we know that the data of a country was parsed, so we can add the dictionary to the array. Also, if the element is any of the two we care about, then we store the found value to the dictionary. At the end, we clear the mutable string from any contents, so it will be ready for new values to be appended to it. The last one:</p>
<pre lang="objc">-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    // Store the found characters if only we&apos;re interested in the current element.
    if ([self.currentElement isEqualToString:@&quot;name&quot;] ||
        [self.currentElement isEqualToString:@&quot;toponymName&quot;]) {

        if (![string isEqualToString:@&quot;\n&quot;]) {
            [self.foundValue appendString:string];
        }
    }
}
</pre>
<p>Here you can see why the <em>currentElement</em> property is needed for. In case that the current element is any of the two we are interested in, then we keep the actual values found between the opening and closing tags. If you notice, you&#x2019;ll see that I check for the new line string (&#x201C;\n&#x201D;), and if the found string is other than that, then I&#x2019;m appending it to the <em>foundValue</em> property. That&#x2019;s because after having tested the app, I noticed that a new line string was parsed before the country name, so this is just a workaround to that problem.</p>
<p>Our app now is capable to download XML data, and to parse it successfully. What we have only left, is to display it.</p>
<h2>Populating the Parsed Data</h2>
<p>In the starter app you downloaded, there&#x2019;s already a table view with an initial implementation, waiting for us to do the proper modifications and display our data. As you may have guessed, the datasource of the table view is going to be the <em>arrNeighboursData</em> array. We&#x2019;ll begin working on the data display by going first to the <em>tableView:numberOfRowsInSection:</em> method. In this one, replace this:</p>
<pre lang="objc">-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 0;
}
</pre>
<p>With this:</p>
<pre lang="objc">-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrNeighboursData.count;
}
</pre>
<p>By doing that, the table view will return as many rows as the neighbour countries are.</p>
<p>Next, let&#x2019;s go to the <em>tableView:cellForRowAtIndexPath:</em> method and let&#x2019;s display our data. Before I give you the implementation, let me remind you that a dictionary object exists in every single position of the array. Let&#x2019;s see the method now:</p>
<pre lang="objc">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@&quot;cell&quot;];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@&quot;Cell&quot;];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    cell.textLabel.text = [[self.arrNeighboursData objectAtIndex:indexPath.row] objectForKey:@&quot;name&quot;];
    cell.detailTextLabel.text = [[self.arrNeighboursData objectAtIndex:indexPath.row] objectForKey:@&quot;toponymName&quot;];

    return cell;
}
</pre>
<p>As you see, in the text label of the cell we assign the name of the country, and we set the toponym name to the subtitle label.</p>
<p>Everything is ready now, so you can go and try the app. After you have typed a country name in the initial view controller, tap on the <em>Neighbour Countries</em> cell to make the app download and parse the neighbour countries of the one you chose. Then, wait until the new data appear on the table view we just set up.</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/08/t17_11_sample_neighbours.png" alt="Understanding XML and JSON Parsing in iOS Programming" class="aligncenter size-full wp-image-3922" srcset="https://www.appcoda.com/content/images/wordpress/2014/08/t17_11_sample_neighbours.png 247w, https://www.appcoda.com/content/images/wordpress/2014/08/t17_11_sample_neighbours-164x300.png 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<h2>Summary</h2>
<p>Performing simple but crucial operations over JSON and XML data, is proved to be a relatively simple job. <em>NSJSONSerialization</em> and <em>NSXMLParser</em> classes are both very handy and powerful, and once you know how to use them you can work with the two respective data formats fast and painlessly. As you found out while you were reading this tutorial, I didn&#x2019;t get into many, hard details of each class. I did this on purpose, as my primary target was to give you a way to start working with them, not to turn you into experts at once. In many cases, what I showed you here is just enough to let you handle any data your app is about to manage, but even in the opposite case, you now know the tools you should use. </p>
<p>For your reference, you can <a href="https://dl.dropboxusercontent.com/u/2857188/JSONXMLFinal.zip?ref=appcoda.com">download the complete Xcode project from here</a>.</p>
<p>As always, I hope you found this tutorial useful. Until next time, leave us your thoughts or anything else you wish to share with us!</p>

<!--kg-card-end: html-->
]]></content:encoded></item><item><title><![CDATA[How to Access iOS Calendar, Events and Reminders Using Event Kit Framework]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>One of the not so well-known frameworks existing on iOS (and Mac OS), is the <strong>Event Kit</strong> framework. This framework has one purpose only, to let us access the calendars, the events and the reminders of a device, and work with them. If you have ever been wondered about how</p>]]></description><link>https://www.appcoda.com/ios-event-kit-programming-tutorial/</link><guid isPermaLink="false">66612a0f166d3c03cf01137b</guid><category><![CDATA[iOS Programming]]></category><category><![CDATA[Objective C]]></category><dc:creator><![CDATA[Gabriel Theodoropoulos]]></dc:creator><pubDate>Wed, 16 Jul 2014 13:44:43 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2014/07/event-kit-featured.jpg" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://www.appcoda.com/content/images/wordpress/2014/07/event-kit-featured.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework"><p>One of the not so well-known frameworks existing on iOS (and Mac OS), is the <strong>Event Kit</strong> framework. This framework has one purpose only, to let us access the calendars, the events and the reminders of a device, and work with them. If you have ever been wondered about how you can create custom events through your app, or how to set reminders without using the Reminders app, then the Event Kit is the answer you&#x2019;re looking for. Through this tutorial, you will have the chance to meet it, as you&#x2019;ll get to know the most important aspects of it.</p>
<p>Before we start working with it, I think it would be useful to mention a few facts about the Event Kit framework. What actually the framework does, is to provide access to the Calendar and Reminders apps, and make your own app capable of retrieving information, or adding new. Behind of both of these apps, there is the same database, named <em>Calendar Database</em>. What you can do with the framework is to create, edit and delete both events and reminders. Events are displayed in the Calendar app, while reminders are (obviously) displayed in the Reminders app. Further than that, you are given the ability to create or delete calendars, and furthermore, to perform more advanced tasks, such as settings alarms for an upcoming event or reminder, or making them recurring.</p>
<p>When using the Event Kit framework, you should always have in mind that the user must grant access to either Calendar or Reminders apps. Upon the first launch of an app that uses the framework, an alert view asking for the user consent must appear, and it&#x2019;s up to users to decide whether your app will be able to work with any of the above resources. After all, asking for user permissions is something that always happen in cases of frameworks that deal with other apps or resources of the iOS. Therefore, you should check if user has granted access, and then make the related to Event Kit features available.</p>
<p>As always, I recommend you to go through the Apple documentation as well for getting a greater level of understanding on the topic. Having said all that, let&#x2019;s move on to make our introduction to the sample app of this tutorial.</p>
<h2>Demo App Overview</h2>
<p>Unlike to the most of the tutorials, in this one we are not going to create an app from the scratch. On the contrary, you should get a starter app from <a href="https://dl.dropboxusercontent.com/u/2857188/EventKitStarterApp.zip?ref=appcoda.com">here</a> in which I&#x2019;ve already made an initial preparation. All the necessary view controllers, connections, and the basic structure have been created and configured. What we have to do, is to apply all the logic lying behind the app.</p>
<p>Before I present you all the aspects of the starter app, let me say a few words about what we&#x2019;ll do in this tutorial. My goal is to make you familiar with the most important Event Kit classes, and the most important tasks of them. There are three major entities that one can work with: Calendar, events and reminders. There are great similarities on event and reminder handling, therefore we&#x2019;ll focus only on events. We&#x2019;ll see how to create, load, delete and display events, but not just that. We&#x2019;ll also see how to add <em>alarms</em> to an event, and how to make a repeated, or in other words a <em>recurring</em> event. Further than that, we&#x2019;ll focus on calendars too. We&#x2019;ll learn how to create a new calendar, how to load and display existing calendars, and how to delete them. Everything will be presented in great details, performing one step at the time.</p>
<p>A couple of words about the starter app now. First of all, I must say that the sample app is a navigation based one. For managing all the aspects of the Event Kit framework, we&#x2019;ll create a new class in which we&#x2019;ll keep adding extra functionalities as we&#x2019;ll move forward to the implementation. Regarding the view controllers, here&#x2019;s in short which they are:</p>
<ul>
<li><em>ViewController</em>: This is the default view controller created automatically with the project. In this one, we&#x2019;ll display all the events of a selected calendar.</li>
<li><em>CalendarsViewController</em>: In this one, we&#x2019;ll display all the local calendars existing on the device or the Simulator. Also, besides than simply showing calendars, we&#x2019;ll be able to add new or delete existing ones.</li>
<li><em>EditEventViewController</em>: This is a quite important one, as we&#x2019;ll do much of our work here. This is the place where we&#x2019;ll edit a new event, we&#x2019;ll set alarms and make our events recurring.</li>
<li><em>DatePickerViewController</em>: It&#x2019;s clearly an auxiliary view controller. We won&#x2019;t do anything on that, but we&#x2019;ll use it to pick dates when it&#x2019;s needed.</li>
</ul>
<p>Lastly, you&#x2019;ll find out that you&#x2019;ll be able to test the app almost at every step of the development. You can do so either on Simulator, or on a real device.</p>
<p>Let&#x2019;s see some action now, as we have a lot of work to do.</p>
<h2>The EventManager Class</h2>
<p>Let&#x2019;s get started by creating a new class which we&#x2019;ll use to manage the various Event Kit related tasks. We will name this class <strong>EventManager</strong>, and through it we&#x2019;ll perform all the saving, loading, deleting and more operations.</p>
<p>On Xcode, go to the <strong>File &gt; New &gt; File&#x2026;</strong> menu, and wait for the guide to appear. Then, select the <strong>Objective-C class</strong> option as the template for the new file, in the <strong>Cocoa-Touch</strong> category under the <strong>iOS</strong> section.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_1_add_file1.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework" class="aligncenter size-full wp-image-3845" srcset="https://www.appcoda.com/content/images/wordpress/2014/07/t16_1_add_file1.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/07/t16_1_add_file1-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Click on the Next button, and at the second step make sure that in the <strong>Subclass of</strong> field the <strong>NSObject</strong> value is set. If not, then start typing it and Xcode will suggest it. In the <strong>Class</strong> field set the name of our class, which is <strong>EventManager</strong> as we already said.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_2_add_file2.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework" class="aligncenter size-full wp-image-3846" srcset="https://www.appcoda.com/content/images/wordpress/2014/07/t16_2_add_file2.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/07/t16_2_add_file2-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Click on the Next button once again, and finally click on the Create to get finished.</p>
<p>After the pair of the new files appear on the Project Navigator, click on the <em>EventManager.h</em> file to edit it. During the implementation of the project, we are going to declare various properties and methods in here. However, the most important property and the one that we&#x2019;ll start with, is an object of the <strong>EKEventStore</strong> class. This class is responsible in the Event Kit for handling almost everything: events, reminders, alarms, etc. As you&#x2019;ll find out later, most of the important tasks will be performed using that property. Having said that, here&#x2019;s the declaration:</p>
<pre lang="objc">@interface EventManager : NSObject

@property (nonatomic, strong) EKEventStore *eventStore;

@end
</pre>
<p>When using frameworks that deal with iOS features or built-in apps, such as the Calendar, the Reminders, or the Photos app, it&#x2019;s necessary to get user permissions for accessing and modifying the resources you want. That happens with the Event Kit framework too. When our app will be launched for first time, a message asking for permissions will be shown to the user, and our app will be able to access the necessary resources (such as calendars) if only the user allows so. If there&#x2019;s no user consent, then a wall will exist between the app and the wanted resources, and nothing will work. In our app, such a message should appear when the <em>ViewController</em> view controller gets loaded, where the events of a calendar will be listed. To let us know whether the user has granted access or not, we will use a boolean value. That value will be saved to the user defaults (<em>NSUserDefaults</em>) dictionary, and it will be retrieved upon subsequent launches of the app. So, let&#x2019;s declare it:</p>
<pre lang="objc">@interface EventManager : NSObject
...
@property (nonatomic) BOOL eventsAccessGranted;

@end
</pre>
<p>Now, open the <em>EventManager.m</em> file to implement the init method of the class. At the moment, we&#x2019;ll do just two things:</p>
<ol>
<li>We will initialize the <em>eventStore</em> object.</li>
<li>We will check if a key for the <em>eventsAccessGranted</em> exists in the user defaults dictionary, and if so, we&#x2019;ll load its value.
<ul>
<li>(instancetype)init<br>
{<br>
self = [super init];<br>
if (self) {<br>
 self.eventStore = [[EKEventStore alloc] init];<p></p>
<pre lang="objc">NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

// Check if the access granted value for the events exists in the user defaults dictionary.
if ([userDefaults valueForKey:@&quot;eventkit_events_access_granted&quot;] != nil) {
    // The value exists, so assign it to the property.
    self.eventsAccessGranted = [[userDefaults valueForKey:@&quot;eventkit_events_access_granted&quot;] intValue];
}
else{
    // Set the default value.
    self.eventsAccessGranted = NO;
}        
</pre>
<p>}<br>
return self;<br>
}</p></li>
</ul>
</li>
</ol>
<p>As you see in the code snippet above, I used the * eventkit_events_access_granted* key name, but that&#x2019;s something you can change if you don&#x2019;t like it. Later, we&#x2019;ll add a few more stuff in the init method.</p>
<p>Now let&#x2019;s go to see how the <em>EventManager</em> class can be used. It&#x2019;s quite important to always have in mind that the initialization of the <em>eventStore</em> object is a time-consuming process. Therefore, Apple strictly recommends to use one instance of that class for performing app-wide tasks, and not to initialize a new object every time that a feature of the Event Kit framework should be used. Following that rule, we are going to declare and initialize such an object in the <em>AppDelegate</em> class, and we are going to use it in all the view controllers of our app.</p>
<p>Open the <em>AppDelegate.h</em> file, and at the very top of it add the next line:</p>
<pre lang="objc">#import &quot;EventManager.h&quot;
</pre>
<p>Then, declare a new property, named <em>eventManager</em>:</p>
<pre lang="objc">@interface AppDelegate : UIResponder <uiapplicationdelegate>

@property (strong, nonatomic) UIWindow *window;

@property (nonatomic, strong) EventManager *eventManager;

@end
</uiapplicationdelegate></pre>
<p>Click on the <em>AppDelegate.m</em> file on the Project Navigator now, and go to the <em>applicationDidBecomeActive:</em> delegate method. In this one we&#x2019;ll initialize the <em>eventManager</em> object:</p>
<pre lang="objc">- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    self.eventManager = [[EventManager alloc] init];

}
</pre>
<p>At this point, the first implementation of the <em>EventManager</em> class is over, but we&#x2019;ll keep adding new code along our way. Also, by declaring the <em>eventManager</em> property in the <em>AppDelegate</em> class, we&#x2019;ll be able to access it from anywhere in the app and manage all the Event Kit related tasks.</p>
<h2>Asking for User Consent</h2>
<p>In the previous section we declared a boolean value that we will use for knowing at any given time whether the user has allowed access to the events of the device. Now, before we go any further, let&#x2019;s see how we can ask for user consent, and how the user response will be stored to the user defaults dictionary. Up to this point, we&#x2019;ve added code to retrieve the value of that boolean property, however we haven&#x2019;t done anything for storing it, so we&#x2019;ll do that here as well.</p>
<p>Begin by opening the <em>ViewController.m</em> file, and by going to the top of the file. We&#x2019;ll ask user to grant access to the events, using a private method. In this private method we&#x2019;ll add the necessary code, and we&#x2019;ll call it from the <em>viewDidLoad</em> method after a small period of time. The delay is necessary, because the event store object requires some time until it gets initialized. At the private class section, add the following declaration:</p>
<pre lang="objc">@interface ViewController ()

...

-(void)requestAccessToEvents;

@end
</pre>
<p>Next, implement it as shown right next:</p>
<pre lang="objc">-(void)requestAccessToEvents{
    [self.appDelegate.eventManager.eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (error == nil) {
            // Store the returned granted value.
            self.appDelegate.eventManager.eventsAccessGranted = granted;
        }
        else{
            // In case of error, just log its description to the debugger.
            NSLog(@&quot;%@&quot;, [error localizedDescription]);
        }
    }];
}
</pre>
<p>The <em>requestAccessToEntityType:completion:</em> method above, expects to be provided with the proper entity type that we&#x2019;re asking access to. There are two values that can be set: Either <em>EKEntityTypeEvent</em> when asking for access to events, or <em>EKEntityTypeReminders</em> when asking for access to reminders. The completion handler is called after the user has made a choice, and the returned <em>granted</em> value is assigned to the respective boolean property of our class. In case that any error occurs, we simply display its description on the debugger.</p>
<p>Now that this method is ready, let&#x2019;s call it in the <em>viewDidLoad</em>:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ..

    // Request access to events.
    [self performSelector:@selector(requestAccessToEvents) withObject:nil afterDelay:0.4];

}
</pre>
<p>By implementing the above stuff we manage to show a default, pre-made alert view to the user the first time the view controller is loaded, but we&#x2019;re unable to store the response yet. As you may have noticed, we didn&#x2019;t call any methods at all for storing the <em>eventsAccessGranted</em> property to the user defaults dictionary, we just assigned the user response to it. So, how are we going to succeed it?</p>
<p>The solution is simple, as we just have to override the <em>setter</em> method of the boolean property. In there, we&#x2019;ll set the property&#x2019;s value, and we&#x2019;ll save it to the user dictionary too. Following that way, we don&#x2019;t have to write any extra method just for saving the boolean value.</p>
<p>Go to the <em>EventManager.m</em> file, and add the next method implementation for the <em>eventAccessGranted</em> property:</p>
<pre lang="objc">-(void)setEventsAccessGranted:(BOOL)eventsAccessGranted{
    _eventsAccessGranted = eventsAccessGranted;

    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:eventsAccessGranted] forKey:@&quot;eventkit_events_access_granted&quot;];
}
</pre>
<p>Notice that we use the <em>_eventsAccessGranted</em> member variable that automatically gets synthesized, instead of the <em>self.eventsAccessGranted</em> property, as that&#x2019;s the proper way to set its value.</p>
<p>Now, the app is able to store the boolean values to the user info dictionary every time a new value is assigned to them.</p>
<p>The next figure illustrates the alert view asking for user consent when the app runs for the first time.</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_3_event_permissions.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework" class="aligncenter size-full wp-image-3847" srcset="https://www.appcoda.com/content/images/wordpress/2014/07/t16_3_event_permissions.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/07/t16_3_event_permissions-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<h2>Listing Calendars</h2>
<p>In order to work with calendars, it&#x2019;s necessary to load the <em>CalendarsViewController</em> view controller and push it to the navigation stack. In the starter app all the necessary connections between the view controllers have been already made, and we only need to add one command for letting it appear. However, we should always check whether the user has allowed access to the events, and if not we shouldn&#x2019;t load the calendars view controller when the <strong>Calendars</strong> bar button item gets tapped.</p>
<p>To do that, open the <em>ViewController.m</em> file, and find the <em>showCalendars:</em> IBAction method definition. In it, add the following code:</p>
<pre lang="objc">- (IBAction)showCalendars:(id)sender {
    if (self.appDelegate.eventManager.eventsAccessGranted) {
        [self performSegueWithIdentifier:@&quot;idSegueCalendars&quot; sender:self];
    }
}
</pre>
<p>That&#x2019;s great, as the calendars view controller will appear now if only the user has granted access to the events of the device.</p>
<p>Let&#x2019;s focus now on how to display all existing event calendars. Before we proceed, I must make clear that there are various types of calendars (such as local, on iCloud, etc). For the sake of the simplicity however, we&#x2019;ll work only with local calendars, meaning with calendars that are stored on the device.</p>
<p>In order to list existing (local) calendars, it&#x2019;s required to have data to show. Therefore, we&#x2019;ll begin here by implementing a custom method on the <em>EventManager</em> class, and in there we&#x2019;ll get all the local calendars from the event store object. Initially, go to the <em>EventManager.h</em> file, and declare the next method:</p>
<pre lang="objc">@interface EventManager : NSObject

...

-(NSArray *)getLocalEventCalendars;

@end
</pre>
<p>That&#x2019;s the first one of a series of methods that we&#x2019;re about to implement in this tutorial. Now, open the <em>EventManager.m</em> file, and define it:</p>
<pre lang="objc">-(NSArray *)getLocalEventCalendars{
    NSArray *allCalendars = [self.eventStore calendarsForEntityType:EKEntityTypeEvent];
    NSMutableArray *localCalendars = [[NSMutableArray alloc] init];

    for (int i=0; i<allcalendars.count; i++) { ekcalendar *currentcalendar="[allCalendars" objectatindex:i]; if (currentcalendar.type="=" ekcalendartypelocal) [localcalendars addobject:currentcalendar]; } return (nsarray *)localcalendars; < pre>
<p>Let&apos;s discuss it a bit. At first, you notice that we get an array with all calendars of any type using the <em>calendarsForEntityType:</em> method of the event store object and by specifying the <em>EKEntityTypeEvent</em> as the kind of the calendars we want to get. Note that this array contains calendars of all types, so we must get only the local ones. For that reason, we initialize a mutable array, and using a loop we check the type of each returned calendar. Every local calendar found in the first array is stored to the mutable one, which is returned at the end. Inside the loop, each calendar (the current calendar) is stored to a <em>EKCalendar</em> object temporarily. As you understand, the <em>EKCalendar</em> class represents a calendar in the Event Kit framework.</p>
<p>Our work here is over for now, so let&apos;s head directly to the <em>CalendarsViewController.m</em> file. The first thing we have to do here, is to declare a private array in which they are going to be stored all the calendars retrieved in the above method. So, go to the private section of the class and declare one. Along with it, declare a private method as well, which we&apos;ll use for loading the calendars:</p>
<pre lang="objc">@interface CalendarsViewController ()

...

@property (nonatomic, strong) NSArray *arrCalendars;

-(void)loadEventCalendars;

@end
</pre>
<p>Let&apos;s implement the <em>loadEventCalendars</em> method:</p>
<pre lang="objc">-(void)loadEventCalendars{
    // Load all local event calendars.
    self.arrCalendars = [self.appDelegate.eventManager getLocalEventCalendars];

    // Reload the table view.
    [self.tblCalendars reloadData];
}
</pre>
<p>What we did in the above snippet is really simple. We just made a call to the new method of the <em>EventManager</em> class, we assigned all found calendars to the <em>arrCalendars</em> array, and we reloaded the table view. The last command is necessary if you want to show the loaded data to the table view.</p>
<p>The above method should be called, and that&apos;s something that we&apos;ll do in the <em>viewDidLoad</em> method:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    // Load all local event calendars.
    [self loadEventCalendars];
}
</pre>
<p>Now, let&apos;s work a bit with the table view methods. At first, let&apos;s specify how many rows should be returned, therefore change the next method as shown:</p>
<pre lang="objc">-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrCalendars.count;
}
</pre>
<p>Note that later we&apos;ll modify it again, but for now we&apos;re fine. What we must do next, is to display the title of each loaded local calendar. Go to the <em>tableView:cellForRowAtIndexPath:</em> method, and replace the <em>return nil;</em> command with the following few lines:</p>
<pre lang="objc">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellCalendar&quot;];

    EKCalendar *currentCalendar = [self.arrCalendars objectAtIndex:indexPath.row];

    cell.textLabel.text = currentCalendar.title;

    return cell;
}
</pre>
<p>Each calendar of the <em>arrCalendars</em> array is firstly assigned to an <em>EKCalendar</em> object, and then its title is set to the <em>textLabel</em> of the cell. If you run the app now, any existing calendars in the device will be listed in our app.</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_4_list_calendars.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework" class="aligncenter size-full wp-image-3848" srcset="https://www.appcoda.com/content/images/wordpress/2014/07/t16_4_list_calendars.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/07/t16_4_list_calendars-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<p>The purpose of this view controller, besides than demonstrating how to create and list calendars, is to let us select one for adding events, so before we finish our work in this section we must indicate the selected calendar on the table view, and store it as well. Actually, each calendar has a unique identifier string, so instead of storing a calendar object when users selects one, we&apos;ll just save its identifier. That&apos;s simpler to do, and by using the identifier we can retrieve the respective calendar from the event store object.</p>
<p>The selected calendar identifier will be assigned to a new property that we&apos;ll add to the <em>EventManager</em> class, therefore go to the <em>EventManager.h</em> file and declare the next one:</p>
<pre lang="objc">@interface EventManager : NSObject

...

@property (nonatomic, strong) NSString *selectedCalendarIdentifier;

@end
</pre>
<p>Before we go back to the <em>CalendarsViewController</em> class, we must perform two tasks: The first one is to override the setter method of this property, so the identifier gets saved to the user defaults dictionary upon value assignment, and the second is to load it in the init method. Let&apos;s see them:</p>
<pre lang="objc">-(void)setSelectedCalendarIdentifier:(NSString *)selectedCalendarIdentifier{
    _selectedCalendarIdentifier = selectedCalendarIdentifier;

    [[NSUserDefaults standardUserDefaults] setObject:selectedCalendarIdentifier forKey:@&quot;eventkit_selected_calendar&quot;];
}
</pre>
<p>There is nothing especially hard here, so let&apos;s go to the init method to load that value, if exists.</p>
<pre lang="objc">- (instancetype)init
{
    self = [super init];
    if (self) {
        ...       

        // Load the selected calendar identifier.
        if ([userDefaults objectForKey:@&quot;eventkit_selected_calendar&quot;] != nil) {
            self.selectedCalendarIdentifier = [userDefaults objectForKey:@&quot;eventkit_selected_calendar&quot;];
        }
        else{
            self.selectedCalendarIdentifier = @&quot;&quot;;
        }
    }
    return self;
}
</pre>
<p>If the <em>eventkit_selected_calendar</em> key exists in the user defaults dictionary then we load the identifier of the selected calendar, otherwise we set the empty string as the value of the <em>selectedCalendarIdentifier</em> property.</p>
<p>Back to the <em>CalendarsViewController</em> now, and in the <em>tableView:cellForRowAtIndexPath:</em> table view method. Continuing its implementation, initially we&apos;ll set the accessory type of the cell to <em>None</em>, meaning no accessory type will exist. Then, we&apos;ll check if the <em>selectedCalendarIdentifier</em> property has a value other than the empty string, and if so, we&apos;ll set the checkmark accessory type to the cell that the respective calendar&apos;s identifier matches to that property&apos;s value. However, if the empty string has been set as the value of the <em>selectedCalendarIdentifier</em> property, then we&apos;ll select by default the first calendar listed on the table view. Here it is:</p>
<pre lang="objc">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ...

    cell.accessoryType = UITableViewCellAccessoryNone;

    if (self.appDelegate.eventManager.selectedCalendarIdentifier.length &gt; 0) {
        if ([currentCalendar.calendarIdentifier isEqualToString:self.appDelegate.eventManager.selectedCalendarIdentifier]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
    }
    else{   
        if (indexPath.row == 0) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
    }

    return cell;
}
</pre>
<p>If you run the app now, you&apos;ll see that the first calendar displayed on the table view is selected by default. If you try to tap on any other calendar (if any exists), you&apos;ll see that the selection doesn&apos;t change. Let&apos;s fix that.</p>
<p>Add the <em>tableView:didSelectRowAtIndexPath:</em> table view method, along with the next three lines:</p>
<pre lang="objc">-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // Deselect the tapped row.
    [[tableView cellForRowAtIndexPath:indexPath] setSelected:NO];

    // Keep the identifier value of the selected calendar.
    self.appDelegate.eventManager.selectedCalendarIdentifier = [[self.arrCalendars objectAtIndex:indexPath.row] calendarIdentifier];

    // Reload the table view.
    [self.tblCalendars reloadData];
}
</pre>
<p>With the first one, the tapped row is deselected. The second one is the most important, as we actually store the identifier of the selected calendar. Finally, we reload the table view so the checkmark accessory type to be displayed next to the selected calendar&apos;s title.</p>
<p>Feel free to try the app again. This time you&apos;ll see that your selection gets changed (as long as you have more than one calendar).</p>
<h2>Creating a Calendar</h2>
<p>If you go to the <em>Main.storyboard</em> file and in the <em>Calendars View Controller</em> scene, you will notice that there&apos;s a prototype cell there which contains a textfield. So far we haven&apos;t used it, but we&apos;re going to do so here. Actually, we will use the textfield for typing a title for a new calendar, which in turn will be stored to the collection of the local calendars.</p>
<p>Besides that, if you run the app and load the <em>CalendarsViewController</em> view controller, you&apos;ll see that at the right side of the navigation bar there is an <em>Edit</em> bar button item. When it&apos;s tapped, we want to set the table view in editing mode, and display the cell with the textfield as well. Because of the editing mode of the table view, at the left side of each cell is going to appear the <em>red minus button</em>, which if tapped it will reveal the <em>Delete</em> button of the respective cell. Also, in the first row a <em>green plus button</em> will appear instead of the red one, as in this row the textfield will appear. Let&apos;s see everything step by step.</p>
<p>Initially, go to the <em>editCalendars</em> IBAction method definition, and add the next couple of lines:</p>
<pre lang="objc">- (IBAction)editCalendars:(id)sender {
    // Set the table in editing mode.
    [self.tblCalendars setEditing:!self.tblCalendars.isEditing animated:YES];

    // Reload the table view.
    [self.tblCalendars reloadData];

}
</pre>
<p>As I said, we want the cell with the textfield to be the first one displayed on the table view when editing. That means that we have to modify the <em>tableView:cellForRowAtIndexPath:</em> method so as to check whether the table view is in editing mode or not, and finally to properly act. Right below you are given the implementation of that method as it should be after doing all the necessary changes:</p>
<pre lang="objc">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellCalendar&quot;];

    if (self.tblCalendars.isEditing) {
        if (indexPath.row == 0) {
            cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellEdit&quot;];

            UITextField *textfield = (UITextField *)[cell viewWithTag:10];
            textfield.delegate = self;
        }
    }

    if (!self.tblCalendars.isEditing || (self.tblCalendars.isEditing &amp;&amp; indexPath.row != 0)) {
        NSInteger row = self.tblCalendars.isEditing ? indexPath.row - 1 : indexPath.row;

        EKCalendar *currentCalendar = [self.arrCalendars objectAtIndex:row];

        cell.textLabel.text = currentCalendar.title;

        if (!self.tblCalendars.isEditing) {
            cell.accessoryType = UITableViewCellAccessoryNone;

            if (self.appDelegate.eventManager.selectedCalendarIdentifier.length &gt; 0) {
                if ([currentCalendar.calendarIdentifier isEqualToString:self.appDelegate.eventManager.selectedCalendarIdentifier]) {
                    cell.accessoryType = UITableViewCellAccessoryCheckmark;
                }
            }
            else{

                if (indexPath.row == 0) {
                    cell.accessoryType = UITableViewCellAccessoryCheckmark;
                }
            }
        }
    }

    return cell;
}
</pre>
<p>Notice the following:</p>
<ul>
<li>If editing, then we access the textfield using its tag value, which I set to 10. Also, we make our class the delegate of the textfield (keep in mind that I already have adopted the <em>UITextFieldDelegate</em> protocol, otherwise the respective line would issue a warning).</li>
<li>The row index of the selected cell is not constant, as when being in editing mode the first row contains the cell with the textfield. Therefore, we dynamically calculate the row index with this line: <em>NSInteger row = self.tblCalendars.isEditing ? indexPath.row - 1 : indexPath.row;</em>.</li>
</ul>
<p>Further than modifying the above method, we must implement the <em>tableView:editingStyleForRowAtIndexPath:</em> too. With this one, the appropriate buttons will be placed at the left side of each cell, as I described earlier.</p>
<pre lang="objc">-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return UITableViewCellEditingStyleInsert;
    }
    else{
        return UITableViewCellEditingStyleDelete;
    }
}
</pre>
<p>Finally, we shouldn&apos;t forget that one more row should be displayed when being in editing mode. Therefore, modify the next method as shown exactly:</p>
<pre lang="objc">-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (!self.tblCalendars.isEditing) {
        return self.arrCalendars.count;
    }
    else{
        return self.arrCalendars.count + 1;
    }
}
</pre>
<p>If you want, go and give the app a try. You&apos;ll notice that when tapping on the Edit button of the navigation bar, the table view enters in editing mode. However, when tapping on the Done button of the keyboard (if you type), or in the green (insert) button, nothing works yet.</p>
<p>What we want from both the Done button of the keyboard and the green button is to create a new calendar using the title typed in the textfield. Instead of writing the same thing twice, we&apos;ll create a private method to do that. Go to the private class section and declare the next method:</p>
<pre lang="objc">@interface CalendarsViewController ()

...

-(void)createCalendar;

@end
</pre>
<p>Let&apos;s see its implementation step by step now. The first thing we should do is to hide the keyboard. To do that, we need to access the textfield, but it is a subview of a cell and there isn&apos;t an IBOutlet property connected to it, so how do we handle it? Here&apos;s is the answer:</p>
<pre lang="objc">UITextField *textfield = (UITextField *)[[self.tblCalendars cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]] viewWithTag:10];
    [textfield resignFirstResponder];
</pre>
<p>Next, we must make sure that the user has actually typed a title, otherwise we shouldn&apos;t proceed:</p>
<pre lang="objc">// In case that no text was typed in the textfield then do nothing.
    if (textfield.text.length == 0) {
        return;
    }
</pre>
<p>When creating a new calendar, two values must be set: The title and the <em>source</em> of the calendar. The source is actually the type of the calendar, and in our case it&apos;s the Local source. Before we see how we specify the source of the calendar, let&apos;s create a new calendar object and let&apos;s set its title:</p>
<pre lang="objc">// Create a new calendar.
    EKCalendar *calendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent
                                                  eventStore:self.appDelegate.eventManager.eventStore];

    // Set the calendar title.
    calendar.title = textfield.text;
</pre>
<p>In the first line you can see that we specify the Event as the entity type of the calendar, and we provide our event store object as the second parameter.</p>
<p>The source of the calendar cannot be assigned directly. Instead, we must go through all the available sources of the event store object using a loop, and when the Local source is found it should be assigned to our calendar. Here it is:</p>
<pre lang="objc">// Find the proper source type value.
    for (int i=0; i<self.appdelegate.eventmanager.eventstore.sources.count; i++) { eksource *source="(EKSource" *)[self.appdelegate.eventmanager.eventstore.sources objectatindex:i]; eksourcetype currentsourcetype="source.sourceType;" if (currentsourcetype="=" eksourcetypelocal) calendar.source="source;" break; } < pre>
<p>With the above lines a new calendar is being created indeed, but it&apos;s not permanently stored. Here&apos;s how we can save it:</p>
<pre lang="objc">NSError *error;
    [self.appDelegate.eventManager.eventStore saveCalendar:calendar commit:YES error:&amp;error];

    // If no error occurs then turn the editing mode off, store the new calendar identifier and reload the calendars.
    if (error == nil) {
        // Turn off the edit mode.
        [self.tblCalendars setEditing:NO animated:YES];

        // Store the calendar identifier.
        [self.appDelegate.eventManager saveCustomCalendarIdentifier:calendar.calendarIdentifier];

        // Reload all calendars.
        [self loadEventCalendars];
    }
    else{
        // Display the error description to the debugger.
        NSLog(@&quot;%@&quot;, [error localizedDescription]);
    }
</pre>
<p>In case that no error occurs, then we turn off the editing mode of the table view, we save the identifier of the newly created calendar and finally we reload all calendars so they properly be displayed to the table view. But wait a minute, what&apos;s that <em>saveCustomCalendarIdentifier:</em> method?</p>
<p>As you have probably guessed, that&apos;s one more method we&apos;ll implement in the <em>EventManager</em> class, but before doing so, it&apos;s important to tell you what is for. So, it is used to store the identifier strings of the calendars we create in our demo app to the user defaults dictionary. That&apos;s not necessary in a real app to happen, but in our case I want to let us know what calendars were created by our app and what not. Later, when we&apos;ll have the calendar deletion feature implemented, nobody would like to delete a calendar other than those created by our app, even by mistake. In other words, we store the newly created calendar identifiers for safety reasons.</p>
<p>Before we proceed, let me give you the <em>createCalendar</em> method in one piece:</p>
<pre lang="objc">-(void)createCalendar{
    // Hide the keyboard. To do so, it&apos;s necessary to access the textfield of the first cell.
    UITextField *textfield = (UITextField *)[[self.tblCalendars cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]] viewWithTag:10];
    [textfield resignFirstResponder];

    // In case that no text was typed in the textfield then do nothing.
    if (textfield.text.length == 0) {
        return;
    }


    // Create a new calendar.
    EKCalendar *calendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent
                                                  eventStore:self.appDelegate.eventManager.eventStore];

    // Set the calendar title.
    calendar.title = textfield.text;

    // Set the calendar source.
    calendar.source = EKSourceTypeLocal;


    // Save and commit the calendar.
    NSError *error;
    [self.appDelegate.eventManager.eventStore saveCalendar:calendar commit:YES error:&amp;error];

    // If no error occurs then turn the editing mode off, store the new calendar identifier and reload the calendars.
    if (error == nil) {
        // Turn off the edit mode.
        [self.tblCalendars setEditing:NO animated:YES];

        // Store the calendar identifier.
        [self.appDelegate.eventManager saveCustomCalendarIdentifier:calendar.calendarIdentifier];

        // Reload all calendars.
        [self loadEventCalendars];
    }
    else{
        // Display the error description to the debugger.
        NSLog(@&quot;%@&quot;, [error localizedDescription]);
    }
}
</pre>
<p>Let&apos;s focus now on the <em>saveCustomCalendarIdentifier:</em> method. At first, go to the <em>EventManager.h</em> file to declare it:</p>
<pre lang="objc">@interface EventManager : NSObject

...

-(void)saveCustomCalendarIdentifier:(NSString *)identifier;

@end
</pre>
<p>Before we implement it, let&apos;s give it some thought. As I said, its purpose is to store the identifiers of the newly created calendars, but how can we handle a bunch of them, not only when saving, but when loading them or later when deleting calendars? The best solution that we have at our disposal it to use an array, in which we&apos;ll add all identifiers, and then we&apos;ll store that array to the user defaults dictionary. </p>
<p>That array doesn&apos;t have to be a public one, so go to the <em>EventManager.m</em> file and declare it privately:</p>
<pre lang="objc">@interface EventManager()

@property (nonatomic, strong) NSMutableArray *arrCustomCalendarIdentifiers;

@end
</pre>
<p>As you see it&apos;s a mutable array, because we want to be able to add and (later) remove objects.</p>
<p>Now, we can implement the method:</p>
<pre lang="objc">-(void)saveCustomCalendarIdentifier:(NSString *)identifier{
    [self.arrCustomCalendarIdentifiers addObject:identifier];

    [[NSUserDefaults standardUserDefaults] setObject:self.arrCustomCalendarIdentifiers forKey:@&quot;eventkit_cal_identifiers&quot;];
}
</pre>
<p>At first we add the new identifier string to the array, and then we save the array to the user defaults dictionary.</p>
<p>Let&apos;s go back to the <em>CalendarsViewController.m</em> file, and let&apos;s call the <em>createCalendar</em> method. The first place that should be called from is the <em>textFieldShouldReturn:</em> textfield delegate method:</p>
<pre lang="objc">-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self createCalendar];

    return YES;
}
</pre>
<p>The second place that we should call it from is when tapping on the green insert button, but we must implement another table view method to do that:</p>
<pre lang="objc">-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleInsert) {
        [self createCalendar];
    }
    else{

    }
}
</pre>
<p>So simple... In the <em>else</em> we&apos;ll add some code later, but for the time being we&apos;re perfect.</p>
<p>Give the app a shot again, and try to create a new calendar. If you followed everything step by step, then you can create a new calendar and also see it in the Calendars app of the device/Simulator.</p>
<p><center><img decoding="async" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_5_add_calendar.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework"><img decoding="async" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_6_calendar_app.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework"></center></p>
<h2>Deleting a Calendar</h2>
<p>To delete a calendar, the red Delete button of the respective cell must become visible, and that can be done in two ways: Either by tapping on the red minus button when being in editing mode, or by swiping on the respective cell towards left. When the Delete button gets tapped, it&apos;s our duty to check if the calendar that&apos;s about to be deleted is a custom one created by our app, or it&apos;s a calendar created by the Calendar or any other app. In the second case, we shouldn&apos;t allow users to delete it, therefore we&apos;ll show a relevant message. However, in cases that a calendar can be removed indeed, then we&apos;ll first ask for confirmation and then we&apos;ll proceed to the actual deletion.</p>
<p>We&apos;ll see everything in details, and the place we&apos;ll start from is the one we left off at the previous section. In the <em>tableView:commitEditingStyle:forRowAtIndexPath:</em> we have an empty <em>else</em> case, and the code we&apos;ll add there is executed when the user taps on the Delete button. Let&apos;s see the method fully implemented this time before we proceed:</p>
<pre lang="objc">-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleInsert) {
        [self createCalendar];
    }
    else{
        // Keep the row index of the calendar that&apos;s about to be deleted.
        self.indexOfCalendarToDelete = indexPath.row - 1;

        // Show the confirmation alert view.
        [self confirmCalendarDeletion];
    }
}
</pre>
<p>In the <em>else</em> clause, we added just two lines. In the first one, we store to a property (that doesn&apos;t exist yet) the row index of the cell that contains the calendar that&apos;s about to be deleted. Note that when editing, the first row contains the cell with the textfield, and the calendar listing starts from the index 1. However, the first calendar index in the <em>arrCalendars</em> array is 0, and in order to have a match we decrease the row index by one.</p>
<p>In the second line we call a custom method, which doesn&apos;t exist yet too. In this one, we&apos;ll display the proper message using an alert view. At the moment, Xcode is showing a couple of errors, and that&apos;s because we refer to objects that do not exist, so let&apos;s declare them. Go to the private class section, and add the next lines:</p>
<pre lang="objc">@interface CalendarsViewController ()

...
@property (nonatomic) NSUInteger indexOfCalendarToDelete;

-(void)confirmCalendarDeletion;

@end
</pre>
<p>Let&apos;s see the implementation of the <em>confirmCalendarDeletion</em> method now:</p>
<pre lang="objc">-(void)confirmCalendarDeletion{
    // Check if the selected calendar is a custom one and can be actually deleted.
    NSString *identifier = [[self.arrCalendars objectAtIndex:self.indexOfCalendarToDelete] calendarIdentifier];
    if (![self.appDelegate.eventManager checkIfCalendarIsCustomWithIdentifier:identifier]) {
        // The selected calendar was not created by our app, so we shouldn&apos;t delete it.
        // Show a message to the user.
        [[[UIAlertView alloc] initWithTitle:@&quot;EventKitDemo&quot;
                                    message:@&quot;You are not allowed to delete this calendar.&quot;
                                   delegate:nil
                          cancelButtonTitle:nil
                          otherButtonTitles:@&quot;Okay&quot;, nil] show];
    }
    else{
        // The calendar can be deleted, but first ask for confirmation.
        // Ask for delete confirmation.
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@&quot;EventKitDemo&quot;
                                                        message:@&quot;Are you sure you want to delete the selected calendar?&quot;
                                                       delegate:self
                                              cancelButtonTitle:@&quot;Cancel&quot;
                                              otherButtonTitles:@&quot;Yes, delete&quot;, nil];

        [alert show];
    }
}
</pre>
<p>The logic here is simple: At first we get the identifier string of the calendar that&apos;s about to be deleted. In the respective line, you can see how we use the <em>indexOfCalendarToDelete</em> property. In order to find out whether the calendar is a custom one (created by our app) or not, we use another method of the <em>EventManager</em> class that we&apos;ll implement in a while. If the identifier doesn&apos;t match to any of the saved ones (remember that we previously saved the identifier of every new calendar), then we display a message to the user telling that deleting the selected calendar is not allowed. Otherwise, we ask for confirmation. Notice that we set our class as the delegate of the alert view. I have already adopted the <em>UIAlertViewDelegate</em> protocol in the starter app, so Xcode doesn&apos;t show a warning.</p>
<p>Let&apos;s implement the <em>checkIfCalendarIsCustomWithIdentifier:</em> method now. Initially, go to the <em>EventManager.h</em> class to declare it:</p>
<pre lang="objc">@interface EventManager : NSObject

...

-(BOOL)checkIfCalendarIsCustomWithIdentifier:(NSString *)identifier;

@end
</pre>
<p>Next, its implementation:</p>
<pre lang="objc">-(BOOL)checkIfCalendarIsCustomWithIdentifier:(NSString *)identifier{
    BOOL isCustomCalendar = NO;

    for (int i=0; i<self.arrcustomcalendaridentifiers.count; i++) { if ([[self.arrcustomcalendaridentifiers objectatindex:i] isequaltostring:identifier]) iscustomcalendar="YES;" break; } return iscustomcalendar; < pre>
<p>If the calendar is found in the <em>arrCustomCalendarIdentifiers</em> array, then the YES value is returned, otherwise the returned value is NO. Before we go back to the <em>CalendarsViewController</em> class, we must take care of one more thing: That is to load the identifiers array from the user defaults dictionary when an <em>EventManager</em> object is initialized. Go to the init method and add the next lines:</p>
<pre lang="objc">- (instancetype)init
{
    self = [super init];
    if (self) {
        ...       

        // Load the custom calendar identifiers (if exist).
        if ([userDefaults objectForKey:@&quot;eventkit_cal_identifiers&quot;] != nil) {
            self.arrCustomCalendarIdentifiers = [userDefaults objectForKey:@&quot;eventkit_cal_identifiers&quot;];
        }
        else{
            self.arrCustomCalendarIdentifiers = [[NSMutableArray alloc] init];
        }
    }
    return self;
}
</pre>
<p>In case that no identifiers array is found in the user defaults dictionary, then we simply initialize the array.</p>
<p>Back to the <em>CalendarsViewController</em> now, let&apos;s handle the user&apos;s response to the deletion confirmation. In the following code, we first check if the user agrees to delete the calendar. Then, we get the proper calendar from the <em>arrCalendars</em> array, and we remove it using the event store object of the <em>EventManager</em> class. Next, if no problem arises, we check if the deleted calendar was the selected one in the table view (the one with the checkmark). If that&apos;s the case, then we set the empty string value to the <em>selectedCalendarIdentifier</em> property of the <em>eventManager</em> object, and finally we remove the deleted calendar&apos;s identifier from the identifiers collection array. Note that the last action is taken using one more custom method that we&apos;ll create in a while in the <em>EventManager</em> class. Here&apos;s the implementation:</p>
<pre lang="objc">-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    // Delete the selected calendar if user selected so.
    if (buttonIndex == 1) {
        NSString *identifier = [[self.arrCalendars objectAtIndex:self.indexOfCalendarToDelete] calendarIdentifier];

        EKCalendar *calendarToDelete = [self.arrCalendars objectAtIndex:self.indexOfCalendarToDelete];

        NSError *error;
        if ([self.appDelegate.eventManager.eventStore removeCalendar:calendarToDelete commit:YES error:&amp;error]) {
            // Check if the calendar that&apos;s about to be deleted is the selected one.
            if ([self.appDelegate.eventManager.selectedCalendarIdentifier isEqualToString:identifier]) {
                // In this case, set the empty string as the selectedCalendarIdentifier property&apos;s value.
                self.appDelegate.eventManager.selectedCalendarIdentifier = @&quot;&quot;;
            }

            // Remove the current identifier from the collection of the custom calendar identifiers.
            [self.appDelegate.eventManager removeCalendarIdentifier:identifier];

            // Load the calendars once again.
            [self loadEventCalendars];
        }
        else{
            // Simply log the error description.
            NSLog(@&quot;%@&quot;, [error localizedDescription]);
        }
    }
}
</pre>
<p>The actual job is being done using the <em>removeCalendar:commit:error:</em> method of the event store object.</p>
<p>Now, back to the <em>EventManager.h</em> class, let&apos;s declare the next one:</p>
<pre lang="objc">@interface EventManager : NSObject

...

-(void)removeCalendarIdentifier:(NSString *)identifier;

@end
</pre>
<p>The implementation is simple:</p>
<pre lang="objc">-(void)removeCalendarIdentifier:(NSString *)identifier{
    [self.arrCustomCalendarIdentifiers removeObject:identifier];

    [[NSUserDefaults standardUserDefaults] setObject:self.arrCustomCalendarIdentifiers forKey:@&quot;eventkit_cal_identifiers&quot;];
}
</pre>
<p>If you run the app now, you&apos;ll be able to delete your calendars.</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_7_delete_cal_confirmation.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework" class="aligncenter size-full wp-image-3851" srcset="https://www.appcoda.com/content/images/wordpress/2014/07/t16_7_delete_cal_confirmation.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/07/t16_7_delete_cal_confirmation-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<h2>Creating a Simple Event</h2>
<p>In order to create an event, here is what we need to provide Event Kit with:</p>
<ul>
<li>A title</li>
<li>A start date</li>
<li>An end date</li>
<li>A calendar</li>
</ul>
<p>Up to now, we have seen how to deal with calendars and how to select one, so we just have to do the necessary implementation for adding a title and the couple of dates to an event. Almost of our work here is going to take place in the <em>EditEventViewController</em> class, but not only. As we previously did, we&apos;re going to enrich the <em>EventManager</em> class even more by adding new necessary methods and properties that will help us in our mission.</p>
<p>The <em>EditEventViewController</em> view controller is supposed to be pushed to the navigation stack when tapping on the add button (Plus) of the navigation bar. However, we should make it work only when the user has granted us access to the events stored in the device. Going into action, open the <em>ViewController.m</em> file, and locate the <em>createEvent:</em> IBAction method. Add the next simple code segment in order to make the <em>EditEventViewController</em> view controller able to be shown:</p>
<pre lang="objc">- (IBAction)createEvent:(id)sender {
    if (self.appDelegate.eventManager.eventsAccessGranted) {
        [self performSegueWithIdentifier:@&quot;idSegueEvent&quot; sender:self];
    }
}
</pre>
<p>The style of the table view existing in the <em>EditEventViewController</em> view controller is grouped, and the table view will contain initially sections (later we&apos;ll add a third section too). In the first section we are going to have the necessary cells for managing the basic data an event needs, while in the second section we are going to add some <em>alarms</em>. However, in this part we&apos;re going to focus on the first section only, we won&apos;t deal with alarms yet.</p>
<p>Open the <em>EditEventViewController.m</em> file and go to the private class section. The first thing we&apos;re about to do here, is to declare and initialize a few properties that we&apos;ll use for storing the event data (title, dates). Add the next lines:</p>
<pre lang="objc">@interface EditEventViewController ()

...

@property (nonatomic, strong) NSString *eventTitle;

@property (nonatomic, strong) NSDate *eventStartDate;

@property (nonatomic, strong) NSDate *eventEndDate;

@end
</pre>
<p>Now, go to the <em>viewDidLoad</em> method and do the following initializations:</p>
<pre lang="objc">- (void)viewDidLoad
{
    [super viewDidLoad];
    ...    
    // Set initial values.
    self.eventStartDate = nil;
    self.eventEndDate = nil;
}
</pre>
<p>Let&apos;s focus now a bit on the <em>tableView:cellForRowAtIndexPath:</em> table view method. As you see in the starter app, I have already added the following piece of code...</p>
<pre lang="objc">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;

    if (indexPath.section == 0) {
        // If the cell is nil, then dequeue it. Make sure to dequeue the proper cell based on the row.
        if (cell == nil) {
            if (indexPath.row == 0) {
                cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellTitle&quot;];
            }
            else{
                cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellGeneral&quot;];
            }
        }
    }
    else{
        if (cell == nil) {
            cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellGeneral&quot;];
        }
    }

    return cell;
}
</pre>
<p>... which simply dequeues the proper cell in the first section and then it returns it. No logic still applied here, and that&apos;s something we&apos;ll do right now. As you see, for the first row is dequeued the cell that contains the textfield, while for the other two rows is dequeued the cell with the label. What we want to do here is quite straightforward: For the first row, we&apos;ll get the textfield and we&apos;ll set the value of the <em>eventTitle</em> property. For the other two cells, we&apos;ll either display the event&apos;s start and end dates, or we&apos;ll show a message that prompts the user to pick a date. Note that the each date object should be converted into a string object for being able to be assigned to the cell&apos;s label. Right below you&apos;re given the same table view method, where it has been added everything I just described:</p>
<pre lang="objc">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;

    if (indexPath.section == 0) {
        // If the cell is nil, then dequeue it. Make sure to dequeue the proper cell based on the row.
        if (cell == nil) {
            if (indexPath.row == 0) {
                cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellTitle&quot;];
            }
            else{
                cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellGeneral&quot;];
            }
        }


        switch (indexPath.row) {
            case 0:
                // The title of the event.
            {
                UITextField *titleTextfield = (UITextField *)[cell.contentView viewWithTag:10];
                titleTextfield.delegate = self;
                titleTextfield.text = self.eventTitle;
            }
                break;

            case 1:
                // The event start date.
                if (self.eventStartDate == nil) {
                    cell.textLabel.text = @&quot;Select a start date...&quot;;
                }
                else{
                    cell.textLabel.text = [self.appDelegate.eventManager getStringFromDate:self.eventStartDate];
                }
                break;

            case 2:
                // The event end date.
                if (self.eventEndDate == nil) {
                    cell.textLabel.text = @&quot;Select an end date...&quot;;
                }
                else{
                    cell.textLabel.text = [self.appDelegate.eventManager getStringFromDate:self.eventEndDate];
                }
                break;

            default:
                break;
        }
    }
    else{
        if (cell == nil) {
            cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellGeneral&quot;];
        }        
    }

    return cell;
}
</pre>
<p>The new addition here is the <em>getStringFromDate:</em> method, which we must implement in the <em>EventManager</em> class. For starters, go to the <em>EventManager.h</em> file and declare it:</p>
<pre lang="objc">@interface EventManager : NSObject

...

-(NSString *)getStringFromDate:(NSDate *)date;

@end
</pre>
<p>Next, open the <em>EventManager.m</em> file and define it as follows:</p>
<pre lang="objc">-(NSString *)getStringFromDate:(NSDate *)date{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [NSLocale currentLocale];
    [dateFormatter setDateFormat:@&quot;d MMM yyyy, HH:mm&quot;];
    NSString *stringFromDate = [dateFormatter stringFromDate:date];
    return stringFromDate;
}
</pre>
<p>The <em>dateFormatter</em> object is the one here that performs the actual job. Using it, we set the format of the string, and then we convert the given date using that format into a string, which is finally returned. Simple but efficient.</p>
<p>Back to the <em>EditEventViewController.m</em> file again, we want to let our users to be able to pick a start and end date for the event, so we must make the table view respond when tapping on any of the date rows. If you&apos;ve taken a look in the interface of the app, then you saw that there&apos;s a view controller named <em>DatePickerViewController</em> with a date picker in it. I created for general use and just for picking a date, and in the Interface Builder the necessary connections have already been made. What we want to do now is to display that view controller, and to do so we need to add the next table view method:</p>
<pre lang="objc">-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 &amp;&amp; (indexPath.row == 1 || indexPath.row == 2)) {
        [self performSegueWithIdentifier:@&quot;idSegueDatepicker&quot; sender:self];
    }
}
</pre>
<p>The <em>DatePickerViewController</em> class has a delegate method, which is called every time a date is selected, and it is already defined in our file. In there, we must store the picked date to the appropriate date property. In order to find out what date property we should use for assigning the selected date to (<em>eventStartDate</em> or <em>eventEndDate</em>), we&apos;ll check which cell is currently selected. Then, we&apos;ll properly assign the date. Here it is:</p>
<pre lang="objc">-(void)dateWasSelected:(NSDate *)selectedDate{
    // Based on the selected cell, specify what the selected date is purposed for.
    NSIndexPath *indexPath = [self.tblEvent indexPathForSelectedRow];

    if (indexPath.section == 0) {
        // In this case, it&apos;s either the event start or end date.
        if (indexPath.row == 1) {
            // The event start date.
            self.eventStartDate = selectedDate;
        }
        else{
            // The event end date.
            self.eventEndDate = selectedDate;
        }
    }

    // Reload the table view.
    [self.tblEvent reloadData];
}
</pre>
<p>With the couple previous steps, we&apos;ve managed to make our users able to select both the start and the end date of the event, and then display them to the table view. What we haven&apos;t still done is to store the typed title, so let&apos;s do it now in the <em>textFieldShouldReturn:</em> textfield delegate method:</p>
<pre lang="objc">-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    self.eventTitle = textField.text;
    [textField resignFirstResponder];

    return YES;
}
</pre>
<p>At this point, our view controller can successfully display and accept new event data, so we have only left to create and save the new event. That task will take place in the <em>saveEvent:</em> IBAction method. Notice that before saving the event, it&apos;s necessary to check if all the required values have been given by the user. If the title or any of the dates is missing, then we just return from the method without saving at all.</p>
<p>Let&apos;s see the method:</p>
<pre lang="objc">- (IBAction)saveEvent:(id)sender {
    // Check if a title was typed in for the event.
    if (self.eventTitle.length == 0) {
        // In this case, just do nothing.
        return;
    }

    // Check if a start and an end date was selected for the event.
    if (self.eventStartDate == nil || self.eventEndDate == nil) {
        // In this case, do nothing too.
        return;
    }

    // Create a new event object.
    EKEvent *event = [EKEvent eventWithEventStore:self.appDelegate.eventManager.eventStore];

    // Set the event title.
    event.title = self.eventTitle;

    // Set its calendar.
    event.calendar = [self.appDelegate.eventManager.eventStore calendarWithIdentifier:self.appDelegate.eventManager.selectedCalendarIdentifier];

    // Set the start and end dates to the event.
    event.startDate = self.eventStartDate;
    event.endDate = self.eventEndDate;


    // Save and commit the event.
    NSError *error;
    if ([self.appDelegate.eventManager.eventStore saveEvent:event span:EKSpanFutureEvents commit:YES error:&amp;error]) {
        // Call the delegate method to notify the caller class (the ViewController class) that the event was saved.
        [self.delegate eventWasSuccessfullySaved];

        // Pop the current view controller from the navigation stack.
        [self.navigationController popViewControllerAnimated:YES];
    }
    else{
        // An error occurred, so log the error description.
        NSLog(@&quot;%@&quot;, [error localizedDescription]);
    }

}
</pre>
<p>In order to create a new event, we use the <em>EKEvent</em> class of the Event Kit framework. After we have provided it with the proper values, we save and commit it at the same time, using once again the event store object of the <em>EventManager</em> class. As you notice, if the saving is successful, we call the delegate method <em>eventWasSuccessfullySaved</em> to notify the caller class that our job here is ready. The caller in our case is the <em>ViewController</em> class, and we&apos;ll implement the delegate method there in a while. For now, we just call it in advance.</p>
<p>Test the app now if you want and try to create a new event. Even though nothing will appear after creating an event in our app yet, you can see if a new event has been actually created by opening the Calendar app of the device or the Simulator. If you find it there, then congratulations, you just managed to create your first event!</p>
<p><center><img decoding="async" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_8_create_event.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework"><img decoding="async" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_9_event_calendar.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework"></center></p>
<h2>Displaying Events</h2>
<p>The job we have to do here is quite simple and straightforward. In order to display the events for the selected calendar we must perform actually two tasks: To load and show them in the table view existing in the <em>ViewController</em> class. We&apos;re going to create a new method in the <em>EventManager</em> class to load them, but before we do so, let&apos;s make some initial steps in the <em>ViewController.m</em> file.</p>
<p>First of all, it&apos;s necessary to declare an array property. In this array we&apos;ll keep all the events after we have them loaded, and from this array the table view will retrieve its data. Furthermore, we&apos;ll create a simple private method, which will be used to load the events and to refresh the table view.</p>
<p>Let&apos;s get started by going to the private class section. In there, write the next couple of lines:</p>
<pre lang="objc">@interface ViewController ()

...

@property (nonatomic, strong) NSArray *arrEvents;

-(void)loadEvents;

@end
</pre>
<p>Now, let&apos;s go to the <em>EventManager</em> class, in order to create a new public method that we&apos;ll use to load the events for the selected calendar. Open the <em>EventManager.h</em> file, and declare the next method:</p>
<pre lang="objc">@interface EventManager : NSObject

...

-(NSArray *)getEventsOfSelectedCalendar;

@end
</pre>
<p>As you notice, we are going to return an array from the method, so we assign the results to the private array property we previously declared in the <em>ViewController</em> class.</p>
<p>Before we go into definition, let me mention something first. To retrieve the events for a calendar, it&apos;s required to use <em>predicates</em> (<em>NSPredicate</em> object). In the predicate we&apos;ll create, we must specify the time period we want to get events for. For demo reasons only, we&apos;ll specify a two-year time period, meaning a year before and a year after the current date. In your applications, apply your own logic depending on the requirements of your apps, and specify the proper predicates. Besides that, keep in mind that the returned events are not sorted in chronological order. Therefore, in the method we&apos;ll implement right next, you&apos;ll see that we apply some sorting so we get all events in order. As a last note, the Event Kit framework method we&apos;ll use to get the events for the specified time period also accepts an array of calendars. In our app, we work with just one calendar at the time, so we&apos;ll add only the currently selected calendar to that array. Let&apos;s see the method now:</p>
<pre lang="objc">-(NSArray *)getEventsOfSelectedCalendar{
    // Specify the calendar that will be used to get the events from.
    EKCalendar *calendar = nil;
    if (self.selectedCalendarIdentifier != nil &amp;&amp; self.selectedCalendarIdentifier.length &gt; 0) {
        calendar = [self.eventStore calendarWithIdentifier:self.selectedCalendarIdentifier];
    }

    // If no selected calendar identifier exists and the calendar variable has the nil value, then all calendars will be used for retrieving events.
    NSArray *calendarsArray = nil;
    if (calendar != nil) {
        calendarsArray = @[calendar];
    }


    // Create a predicate value with start date a year before and end date a year after the current date.
    int yearSeconds = 365 * (60 * 60 * 24);
    NSPredicate *predicate = [self.eventStore predicateForEventsWithStartDate:[NSDate dateWithTimeIntervalSinceNow:-yearSeconds] endDate:[NSDate dateWithTimeIntervalSinceNow:yearSeconds] calendars:calendarsArray];

    // Get an array with all events.
    NSArray *eventsArray = [self.eventStore eventsMatchingPredicate:predicate];

    // Sort the array based on the start date.
    eventsArray = [eventsArray sortedArrayUsingSelector:@selector(compareStartDateWithEvent:)];

    // Return that array.
    return eventsArray;
}
</pre>
<p>Let&apos;s head back to the <em>ViewController.m</em> file, and let&apos;s implement the <em>loadEvents</em> method:</p>
<pre lang="objc">-(void)loadEvents{
    if (self.appDelegate.eventManager.eventsAccessGranted) {
        self.arrEvents = [self.appDelegate.eventManager getEventsOfSelectedCalendar];

        [self.tblEvents reloadData];
    }
}
</pre>
<p>Note that we firstly check if the user has granted access to the events. The usage of the <em>getEventsOfSelectedCalendar</em> method is quite simple. At the end, we reload the table view data.</p>
<p>After we have this method defined, we must call it too. That should happen in two places: The first one is the <em>viewDidLoad</em> method, and the second one is the delegate method of the <em>EditEventViewControllerDelegate</em> protocol. Let&apos;s see that:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    // Load the events with a small delay, so the store event gets ready.
    [self performSelector:@selector(loadEvents) withObject:nil afterDelay:0.5];
}
</pre>
<p>Note that we don&apos;t call the <em>loadEvents</em> method at once, but after a half of a second. This is done on purpose, because if you remember the event store object requires some time in order to get initialized. Next, the call in the delegate method:</p>
<pre lang="objc">-(void)eventWasSuccessfullySaved{
    // Reload all events.
    [self loadEvents];
}
</pre>
<p>Up to here everything is fine, but don&apos;t forget that we must display the data of the loaded events as well. Let&apos;s begin by going to the <em>tableView:numberOfRowsInSection</em> table view method. In there, replace the <em>return 0;</em> command with the next one:</p>
<pre lang="objc">-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrEvents.count;
}
</pre>
<p>We need as many rows as the number of the events. Next, let&apos;s see the <em>tableView:cellForRowAtIndexPath:</em> table view method. What we&apos;ll do here is easy, so here it is:</p>
<pre lang="objc">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellEvent&quot;];

    // Get each single event.
    EKEvent *event = [self.arrEvents objectAtIndex:indexPath.row];

    // Set its title to the cell&apos;s text label.
    cell.textLabel.text = event.title;

    // Get the event start date as a string value.
    NSString *startDateString = [self.appDelegate.eventManager getStringFromDate:event.startDate];

    // Get the event end date as a string value.
    NSString *endDateString = [self.appDelegate.eventManager getStringFromDate:event.endDate];

    // Add the start and end date strings to the detail text label.
    cell.detailTextLabel.text = [NSString stringWithFormat:@&quot;%@ - %@&quot;, startDateString, endDateString];

    return cell;
}
</pre>
<p>You see that we assign each object of the <em>arrEvents</em> array to an <em>EKEvent</em> object, and then we access the values we want. The prototype cell of this table view contains both a main label and a subtitle label. In the first one, we set the title of the event. In the second, we assign the start and end dates of the event, after having them converted to string objects, and after having concatenated them into one string value.</p>
<p>Go and try the app once again. This time, all the events from any calendar you select are displayed, and even more, when creating a new event is shown to the list directly.</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_10_event_listing.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework" class="aligncenter size-full wp-image-3854" srcset="https://www.appcoda.com/content/images/wordpress/2014/07/t16_10_event_listing.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/07/t16_10_event_listing-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<h2>Editing Events</h2>
<p>We&apos;ll make this tutorial even better if we manage to edit an event. What we&apos;ll really do is to delete and re-create a selected event, after having edited its details of course. The <em>EditEventViewController</em> class already contains the mechanism needed to modify and save an event, so we&apos;ll only perform some adjustments to make it fit to our demanding.</p>
<p>The key to the event editing idea is to store somewhere a unique identifier string that each event has (it&apos;s produced when an event is saved for first time), and using that identifier to load the event details in the <em>EditEventViewController</em> view controller. To store temporarily the identifier of the event that we&apos;re about to edit, we&apos;ll create a new public property to the <em>EventManager</em> class, so we can access it directly later on from the <em>EditEventViewController</em> class.</p>
<p>Open the <em>EventManager.h</em> file, and declare the next string property:</p>
<pre lang="objc">@interface EventManager : NSObject

...

@property (nonatomic, strong) NSString *selectedEventIdentifier;

@end
</pre>
<p>Then, go back to the <em>ViewController.m</em> file, and add the next table view delegate method:</p>
<pre lang="objc">-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    // Keep the identifier of the event that&apos;s about to be edited.
    self.appDelegate.eventManager.selectedEventIdentifier = [[self.arrEvents objectAtIndex:indexPath.row] eventIdentifier];

    // Perform the segue.
    [self performSegueWithIdentifier:@&quot;idSegueEvent&quot; sender:self];
}
</pre>
<p>With that method, the identifier of the selected event will be stored to the property we just created, and the <em>EditEventViewController</em> view controller will appear every time that the respected accessory button gets tapped . Note that the <em>idSegueEvent</em> has already been set in the Interface Builder, so the above code will work at once.</p>
<p>Now, let&apos;s go to the <em>EditEventViewController.m</em> file. For starters, declare an <em>EKEvent</em> object that we&apos;ll use for loading the event with the specified identifier:</p>
<pre lang="objc">@property (nonatomic, strong) AppDelegate *appDelegate;

...

@property (nonatomic, strong) EKEvent *editedEvent;

@end
</pre>
<p>The next thing we have to do here, is to check in the <em>viewDidLoad</em> method whether the <em>selectedEventIdentifier</em> property contains a value. If yes, then the proper event should be loaded, and its details should be set to the subviews of the view controller. If that property doesn&apos;t contain a value (it&apos;s nil or it contains the empty string value), then it&apos;s not the case of an edited event. Let&apos;s see that in action. In the <em>viewDidLoad</em> method add the next code segment:</p>
<pre lang="objc">- (void)viewDidLoad
{
    [super viewDidLoad];
    ...    

    // Check the value of the selectedEventIdentifier property, of the eventManager object.
    // If its length is 0, then a new event is going to be added.
    // If its length is other than 0, then an existing event is going to be edited. In that case, load the event.
    if (self.appDelegate.eventManager.selectedEventIdentifier.length &gt; 0) {
        self.editedEvent = [self.appDelegate.eventManager.eventStore eventWithIdentifier:self.appDelegate.eventManager.selectedEventIdentifier];

        self.eventTitle = self.editedEvent.title;
        self.eventStartDate = self.editedEvent.startDate;
        self.eventEndDate = self.editedEvent.endDate;
    }

}
</pre>
<p>That&apos;s it. In the <em>tableView:cellForRowAtIndexPath:</em> method no changes are required to be made, as we have already set the value of each property shown above to the proper subview. The next modification we should make though, is in the <em>saveEvent:</em> method. In this one, we must check if we are editing an existing event or not, and if so, to delete the existing event as we&apos;re going to save it again. Note that by deleting an event and by re-creating it, its identifier gets changed, but actually we don&apos;t care about that.</p>
<p>Go to the <em>saveEvent:</em> and navigate yourself right above the next line:</p>
<pre lang="objc">EKEvent *event = [EKEvent eventWithEventStore:self.appDelegate.eventManager.eventStore];
</pre>
<p>Then, add the next condition:</p>
<pre lang="objc">if (self.appDelegate.eventManager.selectedEventIdentifier.length &gt; 0) {
        [self.appDelegate.eventManager deleteEventWithIdentifier:self.appDelegate.eventManager.selectedEventIdentifier];
        self.appDelegate.eventManager.selectedEventIdentifier = @&quot;&quot;;
    }
</pre>
<p>As you correctly guess, the <em>deleteEventWithIdentifier:</em> is another public custom method of the <em>EventManager</em> class. Before we work with it, I should just say that these lines are enough for succeeding our goal. The existing event will be deleted, and the rest of the code in this method will create it again. Notice that we set the empty string value again to the <em>selectedEventIdentifier</em> property, so we won&apos;t have any problems if we try to add a new event later.</p>
<p>Now, open the <em>EventManager.h</em> file and declare the new method:</p>
<pre lang="objc">@interface EventManager : NSObject

...

-(void)deleteEventWithIdentifier:(NSString *)identifier;

@end
</pre>
<p>To delete the event, we&apos;ll make use of the event store object again. Here&apos;s the implementation, which is straightforward enough:</p>
<pre lang="objc">-(void)deleteEventWithIdentifier:(NSString *)identifier{
    // Get the event that&apos;s about to be deleted.
    EKEvent *event = [self.eventStore eventWithIdentifier:identifier];

    // Delete it.
    NSError *error;
    if (![self.eventStore removeEvent:event span:EKSpanFutureEvents error:&amp;error]) {
        // Display the error description.
        NSLog(@&quot;%@&quot;, [error localizedDescription]);
    }
}
</pre>
<p>We are ready. Test the app once again, and edit an existing event. You&apos;ll see that when you save it, your changes will be reflected in the <em>ViewController</em> view controller.</p>
<h2>Deleting an Event</h2>
<p>The way we structured the app so far, and the last custom method we created in the <em>EventManager</em> class, allow us to delete an event pretty easily. The only thing we should do, is to implement a new table view delegate method, and use in there the <em>deleteEventWithIdentifier:</em> method we previously defined. Let&apos;s see it:</p>
<pre lang="objc">-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the selected event.
        [self.appDelegate.eventManager deleteEventWithIdentifier:[[self.arrEvents objectAtIndex:indexPath.row] eventIdentifier]];

        // Reload all events and the table view.
        [self loadEvents];
    }
}
</pre>
<p>With this one, every time you swipe your finger on a cell towards left the red Delete button will appear. When tapping it, the respective event will be deleted, and the remaining events will be loaded again so the table view contents remain up to date.</p>
<p>With that fast addition you can try the app out again, and delete existing events.</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_11_delete_event.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework" class="aligncenter size-full wp-image-3855" srcset="https://www.appcoda.com/content/images/wordpress/2014/07/t16_11_delete_event.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/07/t16_11_delete_event-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<h2>Setting Alarms</h2>
<p>Setting alarms for one or more events is useful in cases you want the system to notify you about them before their start date. If you remember, when we implemented the logic of the <em>EditEventViewController</em> we said that the table view is going to have two sections. The first one is for the event details, while the second will be used for setting one or more alarms per event. Here, we&apos;re going to focus on that second section, and we&apos;ll perform all the necessary tasks required for using alarms. Keep in mind that when talking about alarms, we actually talk about the <em>date</em> that an alarm should occur. That date should be prior the start date of an event. Alarms act like local notifications, but it&apos;s not recommended to use them in place of such notifications for other general purposes.</p>
<p>For starters, open the <em>EditEventViewController.m</em> file, and in the private section of the class declare the following array:</p>
<pre lang="objc">@interface EditEventViewController ()

...

@property (nonatomic, strong) NSMutableArray *arrAlarms;

@end
</pre>
<p>In this one we&apos;ll store the alarms we&apos;ll create later. Actually, in this array we&apos;ll keep the date of each alarm (date objects). Now, in the <em>viewDidLoad</em> method initialize it:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...
    self.arrAlarms = [[NSMutableArray alloc] init];

}
</pre>
<p>Then, go to the <em>tableView:numberOfRowsInSection:</em> method and modify the body of the <em>else</em> case as shown below:</p>
<pre lang="objc">-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 3;
    }
    else{
        return self.arrAlarms.count + 1;
    }
}
</pre>
<p>The first row of the second section in the table view will have a permanent cell displaying a prompting message for adding a new alarm. All the alarms created will be listed below that cell, starting from the index 1. That&apos;s also the reason we return the total number of alarms plus one in the above method. Further than that, when tapping on the first row to add a new alarm, the <em>DatePickerViewController</em> view controller will appear to pick a date for the alarm.</p>
<p>Having all that in mind, let&apos;s move to the <em>tableView:cellForRowAtIndexPath:</em> method, and let&apos;s add some code to the <em>else</em> case. As you&apos;ll see, we check what the current row is, and if it&apos;s the first one then we display the prompt message. Otherwise, we get the date matching to an alarm, we convert it to a string object, and we show it. Right next, it&apos;s given the whole method again, fully implemented this time:</p>
<pre lang="objc">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;

    if (indexPath.section == 0) {
        // If the cell is nil, then dequeue it. Make sure to dequeue the proper cell based on the row.
        if (cell == nil) {
            if (indexPath.row == 0) {
                cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellTitle&quot;];
            }
            else{
                cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellGeneral&quot;];
            }
        }

        switch (indexPath.row) {
            case 0:
                // The title of the event.
            {
                UITextField *titleTextfield = (UITextField *)[cell.contentView viewWithTag:10];
                titleTextfield.delegate = self;
                titleTextfield.text = self.eventTitle;
            }
                break;

            case 1:
                // The event start date.
                if (self.eventStartDate == nil) {
                    cell.textLabel.text = @&quot;Select a start date...&quot;;
                }
                else{
                    cell.textLabel.text = [self.appDelegate.eventManager getStringFromDate:self.eventStartDate];
                }
                break;

            case 2:
                // The event end date.
                if (self.eventEndDate == nil) {
                    cell.textLabel.text = @&quot;Select an end date...&quot;;
                }
                else{
                    cell.textLabel.text = [self.appDelegate.eventManager getStringFromDate:self.eventEndDate];
                }
                break;

            default:
                break;
        }
    }
    else{
        if (cell == nil) {
            cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellGeneral&quot;];
        }

        if (indexPath.row == 0) {
            cell.textLabel.text = @&quot;+ Add a new alarm...&quot;;
        }
        else{
            cell.textLabel.text = [self.appDelegate.eventManager getStringFromDate:[self.arrAlarms objectAtIndex:indexPath.row - 1]];

            // No selection for the alarm cells.
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            // No accessory style.
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }

    return cell;
}
</pre>
<p>As I said earlier, we want to load and show the <em>DatePickerViewController</em> view controller when tapping on the first row, therefore we must modify the following method as shown:</p>
<pre lang="objc">-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ((indexPath.section == 0 &amp;&amp; (indexPath.row == 1 || indexPath.row == 2)) ||
        (indexPath.section == 1 &amp;&amp; indexPath.row == 0)) {
        [self performSegueWithIdentifier:@&quot;idSegueDatepicker&quot; sender:self];
    }
}
</pre>
<p>By doing so, the date picker view controller will be presented in three cases: When tapping on the start and end dates of the event, and when adding a new alarm. However, that&apos;s not enough for picking a date for the alarm. It&apos;s necessary to modify the <em>dateWasSelected:</em> delegate method, so we add the selected date to the <em>arrAlarms</em> array. Right next, it&apos;s given the whole method again. The interesting part is the outer <em>else</em> case:</p>
<pre lang="objc">-(void)dateWasSelected:(NSDate *)selectedDate{
    // Based on the selected cell, specify what the selected date is purposed for.
    NSIndexPath *indexPath = [self.tblEvent indexPathForSelectedRow];

    if (indexPath.section == 0) {
        // In this case, it&apos;s either the event start or end date.
        if (indexPath.row == 1) {
            // The event start date.
            self.eventStartDate = selectedDate;
        }
        else{
            // The event end date.
            self.eventEndDate = selectedDate;
        }
    }
    else{
        // In this case, the selected date regards a new alarm.
        [self.arrAlarms addObject:selectedDate];
    }

    // Reload the table view.
    [self.tblEvent reloadData];
}
</pre>
<p>The next step is to edit the <em>saveEvent:</em> IBAction method, so any alarms set to be saved along with the event. Adding an alarm to an event is quite easy, as the <em>EKEvent</em> class provides a method named <em>addAlarm:</em> specifically for this reason. Because it&apos;s possible to set more than one alarms, we&apos;ll use a loop to go through all of the <em>arrAlarms</em> array&apos;s objects, we&apos;ll create an alarm object for each date (<em>EKAlarm</em> object) and finally we&apos;ll add it to the event.</p>
<p>In the <em>saveEvent:</em> method, go right above that point (right before we save the event):</p>
<pre lang="objc">NSError *error;
    if ([self.appDelegate.eventManager.eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&amp;error])
</pre>
<p>There, add that snippet:</p>
<pre lang="objc">// Add any alarms the user has set.
    for (int i=0; i<self.arralarms.count; i++) { get the date for current alarm. nsdate *alarmdate="[self.arrAlarms" objectatindex:i]; create a new ekalarm *alarm="[EKAlarm" alarmwithabsolutedate:alarmdate]; add alarm to event. [event addalarm:alarm]; } < pre>
<p>With this small addition, our events can now have alarms. Before we finish our work here though, it would be nice if we could remove an already set alarm, wouldn&apos;t be? Actually, the easiest way would be to swipe towards left on an alarm cell and make the familiar red Delete button appear. Well, that&apos;s more than easy, as long as we implement the following method:</p>
<pre lang="objc">-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1 &amp;&amp; indexPath.row &gt; 0) {
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            // Remove the respective date from the arrAlarms array.
            [self.arrAlarms removeObjectAtIndex:indexPath.row - 1];

            // Reload the table view.
            [self.tblEvent reloadData];
        }
    }
}
</pre>
<p>There&apos;s one more detail that we shouldn&apos;t overlook here, and it regards the alarms of an event that is being edited. We must display the alarms for an edited event when it&apos;s loaded, but we haven&apos;t done something like that so far. What we should do, is to to get all alarms from the edited event in the <em>viewDidLoad</em> method, and add them to the <em>arrAlarms</em> array. Let&apos;s see that:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    // Check the value of the selectedEventIdentifier property, of the eventManager object.
    // If its length is 0, then a new event is going to be added.
    // If its length is other than 0, then an existing event is going to be edited. In that case, load the event.
    if (self.appDelegate.eventManager.selectedEventIdentifier.length &gt; 0) {
        self.editedEvent = [self.appDelegate.eventManager.eventStore eventWithIdentifier:self.appDelegate.eventManager.selectedEventIdentifier];

        ...

        // If there are alarms, then keep the absolute date of each one.
        if (self.editedEvent.hasAlarms) {
            NSArray *alarms = self.editedEvent.alarms;
            for (int i=0; i<alarms.count; i++) { [self.arralarms addobject:[(ekalarm *)[alarms objectatindex:i] absolutedate]]; } < pre>
<p>A great new feature was just added to our app, so feel free to give it one more try. If you think that&apos;s not working correctly on Simulator, then test it on a device. Set an alarm for an event a bit before its start date, and wait until iOS notifies you.</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_12_alarms.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework" class="aligncenter size-full wp-image-3856" srcset="https://www.appcoda.com/content/images/wordpress/2014/07/t16_12_alarms.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/07/t16_12_alarms-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<h2>Repeating an Event</h2>
<p>A repeating, or in other words, a recurring event, is an event that can be re-scheduled automatically with a predefined frequency. In order to make an event able to be repeated, we must create a <em>recurrence rule</em>, and we necessarily need to set two values: The <em>recurrence frequency</em> and the * recurrence interval*. The frequency can have any of the following values:</p>
<ul>
<li>Daily</li>
<li>Weekly</li>
<li>Monthly</li>
<li>Yearly</li>
</ul>
<p>The interval is an integer number, indicating how often an event will be repeated using the specified frequency. For example, if the recurrence frequency is weekly and the interval is 2, then the event will be repeated every two weeks. Besides these two values, the <em>recurrence end</em> can be also set. In this sample, we&apos;re going to use the event&apos;s end date as the recurrence end date too. After having specified the above two values to a recurrence rule, we set it to an event object.</p>
<p>Our goal in this part is to extend a bit more the <em>EditEventViewController</em> class and to make it capable of making an event recurring. In order to keep things simple, we&apos;ll use an array with some predefined recurring values, which will be displayed to the table view and they will be available for selecting any of them. For the sake of the demo app, we&apos;ll set these predefined values:</p>
<ul>
<li>No repeat</li>
<li>Repeat every day</li>
<li>Repeat every 3 days</li>
<li>Repeat every week</li>
<li>Repeat every 2 weeks</li>
<li>Repeat every month</li>
<li>Repeat every 6 months</li>
<li>Repeat every year</li>
</ul>
<p>Let&apos;s start working now to see everything in action. Make sure you&apos;ve opened the <em>EditEventViewController.m</em> file, and then go to the private section of the class to declare the next two properties:</p>
<pre lang="objc">@interface EditEventViewController ()

...

@property (nonatomic, strong) NSArray *arrRepeatOptions;

@property (nonatomic) NSUInteger indexOfSelectedRepeatOption;


@end
</pre>
<p>The first one is the array that will contain the predefined repeat values. The second property will indicate the index of the selected repeat value in the table view and in the array.</p>
<p>Next, we must initialize the array with the above values, as well as the integer property. In the <em>viewDidLoad</em> method add the following:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    // Initialize the repeat options array.
    self.arrRepeatOptions = @[@&quot;Never&quot;, @&quot;Every day&quot;, @&quot;Every 3 days&quot;, @&quot;Every week&quot;, @&quot;Every 2 weeks&quot;, @&quot;Every month&quot;, @&quot;Every six months&quot;, @&quot;Every year&quot;];

    self.indexOfSelectedRepeatOption = 0;
}
</pre>
<p>Now that we have the repeating options ready, it&apos;s necessary to modify the table view so we display them. Begin by setting the total number of sections:</p>
<pre lang="objc">-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
</pre>
<p>Then, return the proper number of rows for each section:</p>
<pre lang="objc">-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 3;
    }
    else if (section == 1) {
        return self.arrAlarms.count + 1;
    }
    else{
        return self.arrRepeatOptions.count;
    }
}
</pre>
<p>As you see, a new case was added here. Next, let&apos;s set the section title:</p>
<pre lang="objc">-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @&quot;General Settings&quot;;
    }
    else if (section == 1) {
        return @&quot;Alarms&quot;;
    }
    else{
        return @&quot;Repeat Frequency&quot;;
    }
}
</pre>
<p>The most important part now, is to display the repeat values. In the <em>tableView:cellForRowAtIndexPath:</em> table view method, we need to add one more case with the following body:</p>
<pre lang="objc">if (cell == nil) {
            cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellGeneral&quot;];
        }

        // The section with the repeat options.
        cell.textLabel.text = [self.arrRepeatOptions objectAtIndex:indexPath.row];

        if (indexPath.row == self.indexOfSelectedRepeatOption) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else{
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
</pre>
<p>Notice that we check whether the current row is the selected one. If that&apos;s the case, then we use the checkmark accessory type to indicate that. Here&apos;s the whole method implementation once again. Our addition is in the last case:</p>
<pre lang="objc">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;

    if (indexPath.section == 0) {
        // If the cell is nil, then dequeue it. Make sure to dequeue the proper cell based on the row.
        if (cell == nil) {
            if (indexPath.row == 0) {
                cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellTitle&quot;];
            }
            else{
                cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellGeneral&quot;];
            }
        }


        switch (indexPath.row) {
            case 0:
                // The title of the event.
            {
                UITextField *titleTextfield = (UITextField *)[cell.contentView viewWithTag:10];
                titleTextfield.delegate = self;
                titleTextfield.text = self.eventTitle;
            }
                break;

            case 1:
                // The event start date.
                if (self.eventStartDate == nil) {
                    cell.textLabel.text = @&quot;Select a start date...&quot;;
                }
                else{
                    cell.textLabel.text = [self.appDelegate.eventManager getStringFromDate:self.eventStartDate];
                }
                break;

            case 2:
                // The event end date.
                if (self.eventEndDate == nil) {
                    cell.textLabel.text = @&quot;Select an end date...&quot;;
                }
                else{
                    cell.textLabel.text = [self.appDelegate.eventManager getStringFromDate:self.eventEndDate];
                }
                break;

            default:
                break;
        }
    }
    else if (indexPath.section == 1){
        if (cell == nil) {
            cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellGeneral&quot;];
        }

        if (indexPath.row == 0) {
            cell.textLabel.text = @&quot;+ Add a new alarm...&quot;;
        }
        else{
            cell.textLabel.text = [self.appDelegate.eventManager getStringFromDate:[self.arrAlarms objectAtIndex:indexPath.row - 1]];

            // No selection for the alarm cells.
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            // No accessory style.
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    else{
        if (cell == nil) {
            cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellGeneral&quot;];
        }

        // The section with the repeat options.
        cell.textLabel.text = [self.arrRepeatOptions objectAtIndex:indexPath.row];

        if (indexPath.row == self.indexOfSelectedRepeatOption) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else{
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }

    return cell;
}
</pre>
<p>If you run it, you&apos;ll see the repeat options listed successfully on the table view. However, nothing happens yet if you tap on any of them, and the first option always remains the selected one. Let&apos;s fix that in the <em>tableView:didSelectRowAtIndexPath:</em> table view method, where we&apos;ll just add a new <em>if</em> clause:</p>
<pre lang="objc">-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ...

    if (indexPath.section == 2) {
        self.indexOfSelectedRepeatOption = indexPath.row;

        [self.tblEvent reloadData];
    }
}
</pre>
<p>Now, every time you tap on a repeat option the selection will get changed too. Up to now, we&apos;ve managed to set and show the predefined repeat options, and to properly select any of them. The most important thing however is to create a recurring rule based on the user selection, and then set it to the event upon saving. Before we create the rule though, we must specify the recurrence frequency and interval values. To do so, head to the <em>saveEvent:</em> IBAction method and and add the next code snippet right before the point where we save the event and after the alarms segment:</p>
<pre lang="objc">// Specify the recurrence frequency and interval values based on the respective selected option.
    EKRecurrenceFrequency frequency;
    NSInteger interval;
    switch (self.indexOfSelectedRepeatOption) {
        case 1:
            frequency = EKRecurrenceFrequencyDaily;
            interval = 1;
            break;
        case 2:
            frequency = EKRecurrenceFrequencyDaily;
            interval = 3;
        case 3:
            frequency = EKRecurrenceFrequencyWeekly;
            interval = 1;
        case 4:
            frequency = EKRecurrenceFrequencyWeekly;
            interval = 2;
        case 5:
            frequency = EKRecurrenceFrequencyMonthly;
            interval = 1;
        case 6:
            frequency = EKRecurrenceFrequencyMonthly;
            interval = 6;
        case 7:
            frequency = EKRecurrenceFrequencyYearly;
            interval = 1;

        default:
            interval = 0;
            frequency = EKRecurrenceFrequencyDaily;
            break;
    }
</pre>
<p>Having at our disposal the <em>frequency</em> and <em>interval</em> values, we&apos;re able to create a new recurrence rule:</p>
<pre lang="objc">// Create a rule and assign it to the reminder object if the interval is greater than 0.
    if (interval &gt; 0) {
        EKRecurrenceEnd *recurrenceEnd = [EKRecurrenceEnd recurrenceEndWithEndDate:event.endDate];
        EKRecurrenceRule *rule = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency:frequency interval:interval end:recurrenceEnd];
        event.recurrenceRules = @[rule];
    }
    else{
        event.recurrenceRules = nil;
    }
</pre>
<p>In the above two lines, not only we created the rule, but we added it to the event as well. Note that the event expects an array of rules, but in our case we have just one.</p>
<p>Now the app is capable of setting a recurring event. Before we test it, let&apos;s look at a last, but important detail: What will happen when we&apos;ll edit an existing event? What is going to be the selected repeat option index? By default, the preselected repeat option is the first one, but that would be wrong in cases that another repeat option had been selected. So, we need to fix that now, and to do so we&apos;ll implement a private method. At first declare it:</p>
<pre lang="objc">@interface EditEventViewController ()

...

-(void)determineIndexOfRepeatOption;

@end
</pre>
<p>In its implementation, we&apos;ll retrieve the recurrence rule from the edited event, and based on the frequency and interval values we&apos;ll specify the index of the selected option. Let&apos;s see it:</p>
<pre lang="objc">-(void)determineIndexOfRepeatOption{
    if (self.editedEvent.recurrenceRules != nil &amp;&amp; self.editedEvent.recurrenceRules.count &gt; 0) {
        // Get the frequency and interval values from the recurrence rule of the edited event.
        EKRecurrenceRule *rule = [self.editedEvent.recurrenceRules objectAtIndex:0];

        EKRecurrenceFrequency frequency = rule.frequency;
        NSInteger interval = rule.interval;

        if (interval == 1){
            if (frequency == EKRecurrenceFrequencyDaily) {
                self.indexOfSelectedRepeatOption = 1;
            }
            else if (frequency == EKRecurrenceFrequencyWeekly){
                self.indexOfSelectedRepeatOption = 3;
            }
            else if (frequency == EKRecurrenceFrequencyMonthly){
                self.indexOfSelectedRepeatOption = 5;
            }
            else{
                self.indexOfSelectedRepeatOption = 7;
            }
        }
        else{
            if (frequency == EKRecurrenceFrequencyDaily) {
                self.indexOfSelectedRepeatOption = 2;
            }
            else if (frequency == EKRecurrenceFrequencyWeekly){
                self.indexOfSelectedRepeatOption = 4;
            }
            else{
                self.indexOfSelectedRepeatOption = 6;
            }
        }
    }
}
</pre>
<p>Lastly, we just have to call it. This should happen in the <em>viewDidLoad</em> method, inside the <em>if</em> condition where we check if the event is edited:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    // Check the value of the selectedEventIdentifier property, of the eventManager object.
    // If its length is 0, then a new event is going to be added.
    // If its length is other than 0, then an existing event is going to be edited. In that case, load the event.
    if (self.appDelegate.eventManager.selectedEventIdentifier.length &gt; 0) {
        self.editedEvent = [self.appDelegate.eventManager.eventStore eventWithIdentifier:self.appDelegate.eventManager.selectedEventIdentifier];

        ...

        // Determine the index of the repeat option based on the recurrence rule of the edited event.
        [self determineIndexOfRepeatOption];

        ...
    }

}
</pre>
<p>That&apos;s it. Our app can now set recurring events, so go and give it a try. Create a new event, set its details and finally pick a repeating option. Tap on Save and return to the <em>ViewController</em> view controller to see that... we have a problem! The table view displays multiple occurrences of the new event instead of just once, as follows:</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_13_multiple_event_occurences.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework" class="aligncenter size-full wp-image-3857" srcset="https://www.appcoda.com/content/images/wordpress/2014/07/t16_13_multiple_event_occurences.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/07/t16_13_multiple_event_occurences-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<p>Well, that would definitely should not happen, but on the other hand it&apos;s quite reasonable, because if you remember we use predicates with specific time frame to retrieve the events. The framework returns all the events for the period we specified, regardless if it&apos;s the same, recurring event. To fix this, we have to pay a visit to the <em>getEventsOfSelectedCalendar</em> custom method of the <em>EventManager</em> class, and add a small code segment, where we&apos;ll copy all the retrieved events to another array before we return them. This time, we&apos;ll keep just one occurrence of each event, and we&apos;ll have no problem. Here&apos;s the method fixed (the modifications start after we have retrieved the events):</p>
<pre lang="objc">-(NSArray *)getEventsOfSelectedCalendar{
    // Specify the calendar that will be used to get the events from.
    EKCalendar *calendar = nil;
    if (self.selectedCalendarIdentifier != nil &amp;&amp; self.selectedCalendarIdentifier.length &gt; 0) {
        calendar = [self.eventStore calendarWithIdentifier:self.selectedCalendarIdentifier];
    }

    // If no selected calendar identifier exists and the calendar variable has the nil value, then all calendars will be used for retrieving events.
    NSArray *calendarsArray = nil;
    if (calendar != nil) {
        calendarsArray = @[calendar];
    }

    // Create a predicate value with start date a year before and end date a year after the current date.
    int yearSeconds = 365 * (60 * 60 * 24);
    NSPredicate *predicate = [self.eventStore predicateForEventsWithStartDate:[NSDate dateWithTimeIntervalSinceNow:-yearSeconds] endDate:[NSDate dateWithTimeIntervalSinceNow:yearSeconds] calendars:calendarsArray];

    // Get an array with all events.
    NSArray *eventsArray = [self.eventStore eventsMatchingPredicate:predicate];

    // Copy all objects one by one to a new mutable array, and make sure that the same event is not added twice.
    NSMutableArray *uniqueEventsArray = [[NSMutableArray alloc] init];
    for (int i=0; i<eventsarray.count; i++) { ekevent *currentevent="[eventsArray" objectatindex:i]; bool eventexists="NO;" check if the current event has any recurring rules set. not, no need to run next loop. (currentevent.recurrencerules !="nil" &#038;&#038; currentevent.recurrencerules.count> 0) {
            for (int j=0; j<uniqueeventsarray.count; j++) { if ([[[uniqueeventsarray objectatindex:j] eventidentifier] isequaltostring:currentevent.eventidentifier]) the event already exists in array. eventexists="YES;" break; } does not exist to new array, then add it now. (!eventexists) [uniqueeventsarray addobject:currentevent]; sort array based on start date. uniqueeventsarray="(NSMutableArray" *)[uniqueeventsarray sortedarrayusingselector:@selector(comparestartdatewithevent:)]; return that (nsarray *)uniqueeventsarray; < pre>
<p>If you run the app again, you&apos;ll see that the same event doesn&apos;t appear more than once now.</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/07/t16_14_set_recurring_event.jpg" alt="How to Access iOS Calendar, Events and Reminders Using Event Kit Framework" class="aligncenter size-full wp-image-3858" srcset="https://www.appcoda.com/content/images/wordpress/2014/07/t16_14_set_recurring_event.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/07/t16_14_set_recurring_event-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<h2>Summary</h2>
<p>This tutorial was an effort to help you meet the world of calendars and events. As you may conclude, working with Event Kit is a quite straightforward process, as nothing especially difficult is required to be done. Working with all the stuff we met here is something that maybe will be needed sooner or later in your programming life, and knowing how to deal with it will surely save you a significant amount of time. Besides that, the class we created and used for managing the framework can be extended and evolved, and ultimately become a useful tool that you can add in your programming toolbox. Closing, I&apos;d like to believe that this tutorial will become handy to all of you, and as always, let me know your thoughts.</p>
<p>For your reference, you can <a href="https://dl.dropboxusercontent.com/u/2857188/EventKitDemo.zip?ref=appcoda.com">download the complete Xcode project from here</a>.</p>

<!--kg-card-end: html-->
</uniqueeventsarray.count;></eventsarray.count;></pre></alarms.count;></pre></self.arralarms.count;></pre></self.arrcustomcalendaridentifiers.count;></pre></self.appdelegate.eventmanager.eventstore.sources.count;></pre></allcalendars.count;></pre>]]></content:encoded></item><item><title><![CDATA[How to Use SQLite to Manage Data in iOS Apps]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>Among the numerous applications existing on the App Store today, it would be hard for someone to find more than a few of them that do not deal with data. Most of the apps handle some sort of data, no matter in what format they are, and always perform some</p>]]></description><link>https://www.appcoda.com/sqlite-database-ios-app-tutorial/</link><guid isPermaLink="false">66612a0f166d3c03cf011379</guid><category><![CDATA[iOS Programming]]></category><category><![CDATA[Objective C]]></category><dc:creator><![CDATA[Gabriel Theodoropoulos]]></dc:creator><pubDate>Tue, 01 Jul 2014 00:53:56 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2014/06/sqlite-database.jpg" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://www.appcoda.com/content/images/wordpress/2014/06/sqlite-database.jpg" alt="How to Use SQLite to Manage Data in iOS Apps"><p>Among the numerous applications existing on the App Store today, it would be hard for someone to find more than a few of them that do not deal with data. Most of the apps handle some sort of data, no matter in what format they are, and always perform some actions upon it. There are various solutions offered to developers for storing and managing data, and usually each one of them is suitable for different kind of applications. However, when working with large amount of data, the preferred method it seems like a one-way path: That is the use of a database.</p>
<p>Indeed, making use of a database can solve various kind of problems that should be solved programmatically in other cases. For programmers who love working with databases and SQL, this is the favorite data-managing method at 90% of the cases, and the first think that crosses their minds when talking about data. Also, if you were used to working with other databases or database management systems (DBMSs), then you&#x2019;ll really appreciate the fact that you can keep applying your SQL knowledge in the iOS platform as well.</p>
<p>The database that can be used by apps in iOS (and also used by iOS) is called <strong>SQLite</strong>, and it&#x2019;s a <em>relational database</em>. It is contained in a C-library that is embedded to the app that is about to use it. Note that it does not consist of a separate service or daemon running on the background and attached to the app. On the contrary, the app runs it as an integral part of it. Nowadays, SQLite lives its third version, so it&#x2019;s also commonly referred as <em>SQLite 3</em>.</p>
<p><img loading="lazy" decoding="async" width="800" height="533" src="http://www.appcoda.com/wp-content/uploads/2014/06/sqlite-database.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3808" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/sqlite-database.jpg 800w, https://www.appcoda.com/content/images/wordpress/2014/06/sqlite-database-450x300.jpg 450w" sizes="(max-width: 800px) 100vw, 800px"></p>
<p>SQLite is not as powerful as other DMBSs, such as MySQL or SQL Server, as it does not include all of their features. However, its greatness lies mostly to these factors:</p>
<ul>
<li>It&#x2019;s lightweight.</li>
<li>It contains an embedded SQL engine, so almost all of your SQL knowledge can be applied.</li>
<li>It works as part of the app itself, and it doesn&#x2019;t require extra active services.</li>
<li>It&#x2019;s very reliable.</li>
<li>It&#x2019;s fast.</li>
<li>It&#x2019;s fully supported by Apple, as it&#x2019;s used in both iOS and Mac OS.</li>
<li>It has continuous support by developers in the whole world and new features are always added to it.</li>
</ul>
<p>Focusing now on our tutorial, let me start by stating that my goal is not to show you how to become a SQLite expert. Instead, my plan is to implement a database class step by step, which will utilize the most important features of the SQLite library, but it will also become a reusable tool for your own applications. Unfortunately, even though SQLite is supported by Apple, a mechanism or a pre-made database management library does not exist. Going into more details, the database class that we will implement will be capable of executing all the standard SQL queries (<em>select</em>, <em>insert</em>, <em>update</em>, <em>delete</em>). The most important is that we&#x2019;ll create it in such way, so it accepts clear SQL statements, and if you had worked with SQL in the past, you&#x2019;ll definitely know what to do here too.</p>
<p>Besides the database class that we&#x2019;ll develop, we&#x2019;ll also create a sample application to test it and to see it in action. More details about that you&#x2019;ll find in the next section though. Note that the queries we&#x2019;ll write in the demo app will be simple enough for the sake of the tutorial, however be sure that more complex queries can be executed as well.</p>
<p>As a final word before we proceed, I would recommend to make a web search and read some more stuff about the SQLite itself. Of course, the first one should be the the official website.</p>
<h2>App Overview</h2>
<p>One could say that this tutorial is composed by three parts. In the first and most important one, we are going to create a new class and in there we&#x2019;ll implement all the database handling. As I have already said in the introduction, after we have it finished, you can take it and use it as a reusable component to your own apps. In the second part we are going to leave Xcode for a while, as it&#x2019;s necessary to work in the Terminal and in the SQLite command line environment. There, we will create a simple database, which we will add to the project and use it. Finally, in the third part, we are going to implement a sample application where we will make use of both the database class and the database file. More specifically about the third part, we will make the necessary configuration in the Interface Builder, and then we&#x2019;ll write the required code so we&#x2019;ll have a fully functional app in which the database class will have the most significant role.</p>
<p>Regarding the database class that we will create in a while, I would say that it can be used as-is in the most cases of applications. To tell the truth, I rarely needed to do any updates or modifications to the class&#x2019;s code after its initial implementation, as it has been suitable for every app I developed or have been developing. Nevertheless, keep in mind that even though we will build a reusable tool, you should feel free to change it, evolve it and add any extra features you might think that would be useful for your own needs. Nothing is set of stone.</p>
<p>In the sample database that we will create to test the class, we are going to add just one table. We&#x2019;ll name that table <em>peopleInfo</em>, and it will contain some basic people&#x2019;s data. These will be the first name, the last name and the age. The datatype of the first two fields will be set to text, while the age will be an integer value. For the primary key of the table, we will set an auto-increment integer value. Generally, using such a key is recommended in most of cases, unless special requirements of your app define otherwise. The sample database will be created in Terminal, and then it will be added to the project. Maybe you are wondering if there are any Mac applications that could be used for that purpose, and the answer is that there are. To be honest though, I prefer and like a lot more to use the command line environment, as I think that it consists of the fastest and most efficient way to work with a database.</p>
<p>Finally, focusing a bit more on the sample app, it&#x2019;s necessary to say that it&#x2019;s going to be a <em>navigation based</em> app. However, initially we will create a simple, view-based app, and later through the Interface Builder we will convert it to navigation-based. Furthermore, the app will be parted by two view controllers. In the first view controller, we will display all the records fetched from the database in a table view. Besides than simply listing them, we&#x2019;ll also make our app capable of editing and deleting records. The second view controller will be used to add a new record, or edit an existing one. Upon finishing, our app will be able to perform all the basic kind of queries: <em>select</em> for loading the data, <em>insert</em> for adding new records, <em>update</em> for editing existing records and <em>delete</em> to completely delete a record.</p>
<p>In the animated graphic below you can see the final outcome of our effort in this tutorial:</p>
<p><img loading="lazy" decoding="async" width="313" height="587" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_19_sample.gif" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3800"></p>
<p>Having said all the above, I think is time to get started. We have a long journey ahead of us, so let&#x2019;s don&#x2019;t waste any more time.</p>
<h2>Creating the Project</h2>
<p>Unless we have a very special topic to discuss, the first step will always be the creation of our project. So, let me guide you through the necessary steps and make sure that we get along in all that.</p>
<p>Initially, launch Xcode and wait for the Welcome screen to appear. There, select to create a new project, as shown in the next figure:</p>
<p><img loading="lazy" decoding="async" width="600" height="352" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_1_xcode_welcome.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3782" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_1_xcode_welcome.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_1_xcode_welcome-511x300.jpg 511w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Next, in the first step of the guide that is appeared, select the <strong>Single View Application</strong> template, in the <strong>Application</strong> category, under the <strong>iOS</strong> section.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_2_template1.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3783" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_2_template1.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_2_template1-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Click on the Next button to proceed. In the second step, in the <strong>Product Name</strong> field set the <strong>SQLite3DBSample</strong> as the project&#x2019;s name, and also make sure that the <strong>iPhone</strong> is the selected value in the <strong>Device</strong> drop down control.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_3_template2.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3784" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_3_template2.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_3_template2-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Click on the Next button once again, and in the last step of the guide select a directory in your computer to save the project. Click on the Create button and wait until Xcode prepares the project.</p>
<h2>The SQLite 3 Library</h2>
<p>Before we begin implementing, it&#x2019;s necessary to perform a small prerequisite step. That is to add the appropriate SQLite 3 library to the project, so we can import it later on to our class.</p>
<p>In the Project Navigator on Xcode click on the project name. Next, make sure that the <strong>General</strong> tab is on, and then go to the bottom of the page, in the <strong>Linked Frameworks and Libraries</strong> section. Click on the small plus icon as shown in the next image:</p>
<p><img loading="lazy" decoding="async" width="600" height="672" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_4_general_tab_plus_icon.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3785" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_4_general_tab_plus_icon.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_4_general_tab_plus_icon-267x300.jpg 267w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>In the modal window that appears, type the term <em>sqlite</em>, and from the suggested options select the one with the <strong>libsqlite3.dylib</strong> title.</p>
<p><img loading="lazy" decoding="async" width="400" height="460" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_5_select_library.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3786" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_5_select_library.jpg 400w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_5_select_library-260x300.jpg 260w" sizes="(max-width: 400px) 100vw, 400px"></p>
<p>Finally, click on the Add button and this step is over.</p>
<h2>Creating and Initializing the Database Class</h2>
<p>So, now that the SQLite 3 library has been added to the project, the first thing we are going to do is to create a new class to manage all the database functionality. In this class, we will write all the code needed to execute queries and to load data from the database.</p>
<p>Let&#x2019;s get started by adding a new class file to the project. Go to the <strong>File &gt; New &gt; File&#x2026;</strong> menu of the Xcode, or just hit the Command-N key combination on your keyboard. The familiar Xcode guide will appear. In the first step, select the <strong>Objective-C class</strong> option in the <strong>Cocoa Touch</strong> category, under the <strong>iOS</strong> section.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_6_new_file1.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3787" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_6_new_file1.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_6_new_file1-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Click on the Next button, and in the next step perform two tasks: First, make sure that the <strong>Subclass of</strong> field contains the <strong>NSObject</strong> value. If not, then type it. Next, in the <strong>Class</strong> field type the name of our class, which is <strong>DBManager</strong>.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_7_new_file2.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3788" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_7_new_file2.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_7_new_file2-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>After having done the above, click once again on the Next button, and in the third and last step make sure that the <strong>SQLite3DBSample</strong> target is selected. If not do it now, and click on the Create button. The guide will close and the new class will be ready.</p>
<p>Now we have an empty class in our hands, and we just have to write code in it. We&#x2019;ll begin by creating a custom <em>init</em> method, as upon initialization we want to specify the database file name. Click on the <em>DBManager.h</em> file on the Project Navigator to open it. In there, add the following declaration:</p>
<pre lang="objc">@interface DBManager : NSObject

-(instancetype)initWithDatabaseFilename:(NSString *)dbFilename;

@end
</pre>
<p>Now, go to the <em>DBManager.m</em> file, and write the standard definition of all the init methods:</p>
<pre lang="objc">-(instancetype)initWithDatabaseFilename:(NSString *)dbFilename{
    self = [super init];
    if (self) {

    }
    return self;
}
</pre>
<p>As I have already said, the original database file will reside in the application&#x2019;s bundle (in other words, the app package). Our mission is to make a copy of that file to the application&#x2019;s documents directory, and work with that copy later on. Note that you should never work directly with a file existing in the app bundle, especially if your app is going to modify it. Always make a copy of it to the documents directory.</p>
<p>Focusing on the init method again, we&#x2019;re going:</p>
<ol>
<li>To specify the path to the documents directory of the app and store it to a property .</li>
<li>To store the database filename that is provided as an argument in the above init method to another property.</li>
<li>To copy the database file from the app bundle into the documents directory if that&#x2019;s necessary.</li>
</ol>
<p>We&#x2019;ll use properties to store the documents directory and the database filename values, as we&#x2019;ll need them later as well.</p>
<p>Having said all the above, go at the top of the file and create the private class section, by declaring at the same time the two properties as described.</p>
<pre lang="objc">@interface DBManager()

@property (nonatomic, strong) NSString *documentsDirectory;
@property (nonatomic, strong) NSString *databaseFilename;

@end
</pre>
<p>Now, once being at the top of the file, make the next import:</p>
<pre lang="objc">#import <sqlite3.h>
</sqlite3.h></pre>
<p>So far, so good. Back to the init method, let&#x2019;s do some initialization. Right next you are given the method again, containing this time all the proper code:</p>
<pre lang="objc">-(instancetype)initWithDatabaseFilename:(NSString *)dbFilename{
    self = [super init];
    if (self) {
        // Set the documents directory path to the documentsDirectory property.
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        self.documentsDirectory = [paths objectAtIndex:0];

        // Keep the database filename.
        self.databaseFilename = dbFilename;

        // Copy the database file into the documents directory if necessary.
        [self copyDatabaseIntoDocumentsDirectory];
    }
    return self;
}
</pre>
<p>At first, we specify the path to the documents directory and we store it to the <em>documentsDirectory</em> property. Next, we assign the database filename to the <em>databaseFilename</em> property, and finally we copy the database file from the app bundle to the documents directory.</p>
<p>As you correctly assume, the <em>copyDatabaseIntoDocumentsDirectory</em> is a custom, private method that we must implement, and in here we&#x2019;ll do the file copying, if needed of course. Surely Xcode have issued an error by now, so let&#x2019;s work against it.</p>
<p>Go back to the private class section, and declare the method as shown below:</p>
<pre lang="objc">@interface DBManager()

@property (nonatomic, strong) NSString *documentsDirectory;
@property (nonatomic, strong) NSString *databaseFilename;

-(void)copyDatabaseIntoDocumentsDirectory;

@end
</pre>
<p>Let&#x2019;s go to the definition right away. What we&#x2019;ll do here is fairly simple: We&#x2019;ll check if the database file exists or not in the documents directory, and if it&#x2019;s not there we&#x2019;ll copy it. Here&#x2019;s the implementation:</p>
<pre lang="objc">-(void)copyDatabaseIntoDocumentsDirectory{
    // Check if the database file exists in the documents directory.
    NSString *destinationPath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
    if (![[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
        // The database file does not exist in the documents directory, so copy it from the main bundle now.
        NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseFilename];
        NSError *error;
        [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&amp;error];

        // Check if any error occurred during copying and display it.
        if (error != nil) {
            NSLog(@&quot;%@&quot;, [error localizedDescription]);
        }
    }
}
</pre>
<p>There&#x2019;s nothing especially difficult in the above method. We are based on the <em>NSFileManager</em> class to check for the file existence and to copy it if needed. It&#x2019;s also quite interesting the way we access the original file in the app bundle: <em>[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseFilename]</em>.</p>
<p>The above method will be called every time that an object of the <em>DBManager</em> class is initialized. If the database file won&#x2019;t be found in the documents directory, then the code in the condition block will be executed, otherwise it will be skipped. Normally, that code should be executed just once per app install, as the database file should always remain in the documents directory after having been copied in there.</p>
<p>So, quickly summarizing, we&#x2019;ve managed to perform two important tasks here: To create the <em>DBManager</em> class files, and to create a custom init method, which makes sure that the database file will exist to the documents directory of the app. Now, we are ready to go deeper in the details of the SQLite 3 database.</p>
<h2>SQLite 3 Functions Preview</h2>
<p>Our next step is to implement the heart of our class, the method that will take care of all the work with the database. However, I believe it would be much better to take a quick look at the SQLite 3 functions that we are going to need first, and then proceed to implementation. There&#x2019;s a great number of functions supported and provided, but we&#x2019;ll need just some of them. Let&#x2019;s see them one by one:</p>
<ul>
<li><strong><em>sqlite3_open</em></strong>: This function is used to create and open a database file. It accepts two parameters, where the first one is the database file name, and the second a handler to the database. If the file does not exist, then it creates it first and then it opens it, otherwise it just opens it.</li>
<li><strong><em>sqlite3_prepare_v2</em></strong>: The purpose of this function is to get a SQL statement (a query) in string format, and convert it to an executable format recognizable by SQLite 3.</li>
<li><strong><em>sqlite3_step</em></strong>: This function actually executes a SQL statement (query) prepared with the previous function. It can be called just once for executable queries (insert, update, delete), or multiple times when retrieving data. It&#x2019;s important to have in mind that it can&#x2019;t be called prior to the <em>sqlite3_preprare_v2</em> function.</li>
<li><strong><em>sqlite3_column_count</em></strong>: This method&#x2019;s name it makes it easy to understand what is about. It returns the total number of columns (fields) a contained in a table.</li>
<li><strong><em>sqlite3_column_text</em></strong>: This method returns the contents of a column in text format, actually a C string (<em>char *</em>) value. It accepts two parameters: The first one is the query converted (compiled) to a SQLite statement, and the second one is the index of the column.</li>
<li><strong><em>sqlite3_column_name</em></strong>: It returns the name of a column, and its parameters are the same to the previous function&#x2019;s.</li>
<li><strong><em>sqlite3_changes</em></strong>: It actually returns the number of the affected rows, after the execution of a query.</li>
<li><strong><em>sqlite3_last_insert_rowid</em></strong>: It returns the last inserted row&#x2019;s ID.</li>
<li><strong><em>sqlite3_errmsg</em></strong>: It returns the description of a SQLite error.</li>
<li><strong><em>sqlite3_finalize</em></strong>: It deletes a prepared statement from memory.</li>
<li><strong><em>sqlite3_close</em></strong>: It closes an open database connection. It should be called after having finished any data exchange with the database, as it releases any reserved system resources.</li>
</ul>
<h2>Core Functionality Implementation</h2>
<p>Now that you&#x2019;ve been provided with a short description of every SQLite function we&#x2019;ll meet next, let&#x2019;s go to the implementation of the core method of our class. In this one, we are going to run both executable and non-executable queries. Based on that, we will make sure to implement it that way so it accepts two parameters: The query itself, and a boolean value indicating whether the query is executable or not. The logic applied in the method is quite simple, but let&#x2019;s give it a look:</p>
<ul>
<li>Initially, we&#x2019;ll perform some necessary initializations, regarding mostly the structures that will store our data (<em>NSMutableArray</em> objects).</li>
<li>Then, we&#x2019;ll open the database and if that&#x2019;s successful, we&#x2019;ll compile the query to a SQLite 3 statement (prepared statement).</li>
<li>If the query is not executable, meaning that is a <em>select</em> statement, we&#x2019;ll fetch the desired data row by row. For each one, we&#x2019;ll get each single column&#x2019;s contents as a text value, and we&#x2019;ll add it to a temporary mutable array. When all the columns of a data row have been read, we&#x2019;ll add the temporary array to the final results array. At the same time, we&#x2019;ll use another array to save the column names, as it&#x2019;s quite possible to become handy when the database class will be used.</li>
<li>If the query is executable, meaning that is an <em>insert</em>, <em>update</em>, or <em>delete</em> statement, things will be much simpler. We&#x2019;ll just execute the query and if the result is successful, then we&#x2019;ll store to properties the affected rows and the last inserted ID values.</li>
<li>In case of any error, we&#x2019;ll just output its description.</li>
<li>Finally, we&#x2019;ll make sure to free up all used resources.</li>
</ul>
<p>Let me now denote a couple of things. First of all, and according to what I said in the above description, we&#x2019;ll get each column&#x2019;s contents as a text value. This is a generic approach and you may think that it doesn&#x2019;t suit to all kind of data existing to a database table. However, don&#x2019;t forget that we want to implement a class that will work for all applications (or the most of them), so our solution shouldn&#x2019;t be oriented to specific data. Moreover, the text (string) results can be converted to other data types and be handled in any desired way by an app.<br>
At second, the fetched results will be stored to a two-dimensional array. Into each index of the results array, there will be another array containing the data of a single row. Personally, I consider this to be the best option for having the result set from the database file to memory. If you wish so, you could try to modify the implementation and use <em>NSDictionary</em> objects instead.</p>
<p>Let&#x2019;s get started with the implementation now. We&#x2019;ll do one step at the time, so we discuss each action we take. Besides that, there are plenty of comments in the code that will help you understand it much better.</p>
<p>First off, go to the private class section, and declare a mutable array property for storing our results, and of course, the private method itself:</p>
<pre lang="objc">@interface DBManager()

...
...
@property (nonatomic, strong) NSMutableArray *arrResults;


-(void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable;

@end
</pre>
<p>If you wonder why this method is private, while it should be public, then the answer is simple: After having finished with it, we&#x2019;ll create two small public methods, where we&#x2019;ll use the first one just to load data from the database, and the second one to run executable queries. Both of those methods will call this, providing each one the proper arguments. Besides that, notice that the query parameter is a <em>const char </em> (a C string) and not a NSString* object. That&#x2019;s because the SQLite functions don&#x2019;t know anything about <em>NSStrings</em>, they just know how to handle C strings.</p>
<p>Next, go to the <em>DBManager.h</em> file, and in the public class section declare the next three properties:</p>
<pre lang="objc">@interface DBManager : NSObject

...
...

@property (nonatomic, strong) NSMutableArray *arrColumnNames;

@property (nonatomic) int affectedRows;

@property (nonatomic) long long lastInsertedRowID;

@end
</pre>
<p>I think there&#x2019;s no need to explain what these properties are for.</p>
<p>Back to the <em>DBManager.m</em> file to get started with the implementation. As you&#x2019;ll see right next, initially we perform four specific tasks: We declare a local SQLite 3 object to handle the database, we set the path to the database file, and we initialize the two array properties (the <em>arrResults</em> and the <em>arrColumnNames</em> arrays).</p>
<pre lang="objc">-(void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable{
    // Create a sqlite object.
    sqlite3 *sqlite3Database;

    // Set the database file path.
    NSString *databasePath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];

    // Initialize the results array.
    if (self.arrResults != nil) {
        [self.arrResults removeAllObjects];
        self.arrResults = nil;
    }
    self.arrResults = [[NSMutableArray alloc] init];

    // Initialize the column names array.
    if (self.arrColumnNames != nil) {
        [self.arrColumnNames removeAllObjects];
        self.arrColumnNames = nil;
    }
    self.arrColumnNames = [[NSMutableArray alloc] init];
}
</pre>
<p>Note that if any previous data exist in any of the arrays, we get rid of them before we initialize the arrays again to make sure that nothing remains on memory.</p>
<p>Next, we must open the database, and if no error occurs we will use the <em>sqlite3_prepare_v2</em> function to convert the query into a executable SQLite part:</p>
<pre lang="objc">    // Open the database.
    BOOL openDatabaseResult = sqlite3_open([databasePath UTF8String], &amp;sqlite3Database);
    if(openDatabaseResult == SQLITE_OK)
        // Declare a sqlite3_stmt object in which will be stored the query after having been compiled into a SQLite statement.
        sqlite3_stmt *compiledStatement;

    // Load all data from database to memory.
    BOOL prepareStatementResult = sqlite3_prepare_v2(sqlite3Database, query, -1, &amp;compiledStatement, NULL);
    if(prepareStatementResult == SQLITE_OK) {
        ...
    }
    ...
}
</pre>
<p>As you see, we check if the database was opened successfully comparing with the <em>SQLITE_OK</em> value. Then, we declare the <em>compiledStatement</em> variable, which is a <em>sqlite3_stmt</em> type, for storing the compiled statement. Finally, we make use of the <em>sqlite3_prepare_v2</em> function, in which we pass the database handler, the query and the compiled statement variable as parameters.</p>
<p>Inside the inner <em>if</em> clause above, we&#x2019;ll check if the query is executable or not. In case it&#x2019;s a <em>select</em> query, we&#x2019;ll load all data specified by the query. Here we go:</p>
<pre lang="objc">// Check if the query is non-executable.
    if (!queryExecutable){
        // In this case data must be loaded from the database.

        // Declare an array to keep the data for each fetched row.
        NSMutableArray *arrDataRow;

        // Loop through the results and add them to the results array row by row.
        while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
            // Initialize the mutable array that will contain the data of a fetched row.
            arrDataRow = [[NSMutableArray alloc] init];

            // Get the total number of columns.
            int totalColumns = sqlite3_column_count(compiledStatement);

            // Go through all columns and fetch each column data.
            for (int i=0; i<totalcolumns; i++){ convert the column data to text (characters). char *dbdataaschars="(char" *)sqlite3_column_text(compiledstatement, i); if there are contents in currenct (field) then add them current row array. (dbdataaschars !="NULL)" { characters string. [arrdatarow addobject:[nsstring stringwithutf8string:dbdataaschars]]; } keep name. (self.arrcolumnnames.count dbdataaschars="(char" *)sqlite3_column_name(compiledstatement, [self.arrcolumnnames store each fetched results array, but first check is actually data. (arrdatarow.count> 0) {
                [self.arrResults addObject:arrDataRow];
            }
        }
    }
</totalcolumns;></pre>
<p>We wrote some code here, so let&#x2019;s discuss it. At first we declare a local array, named <em>arrDataRow</em>. In this one, we&#x2019;ll store each data row fetched from the dataset existing in memory. Then, using the <em>sqlite3_step</em> function, we go through all the results row by row. Inside the <em>while</em> loop, we initialize the <em>arrDataRow</em> array and we get the total number of columns existing in the result set. Then, inside a new <em>for</em> loop, we get each column&#x2019;s contents and we assign them to a <em>char </em> variable. If that value is not null, we add it to the temp <em>arrDataRow</em> array converted to a NSString* object. Next, if we haven&#x2019;t done so already, we store each column name to the <em>arrColumnNames</em> array. Finally, when the <em>for</em> loop is over, we add the fetched data row to the <em>arrResults</em> array.</p>
<p>Let&#x2019;s proceed to the case of an executable query:</p>
<pre lang="objc">    else {
        // This is the case of an executable query (insert, update, ...).

        // Execute the query.
        BOOL executeQueryResults = sqlite3_step(compiledStatement);
        if (executeQueryResults == SQLITE_DONE) {
            // Keep the affected rows.
            self.affectedRows = sqlite3_changes(sqlite3Database);

            // Keep the last inserted row ID.
            self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
        }
        else {
            // If could not execute the query show the error message on the debugger.
            NSLog(@&quot;DB Error: %s&quot;, sqlite3_errmsg(sqlite3Database));
        }
    }
}
else {
    // In the database cannot be opened then show the error message on the debugger.
    NSLog(@&quot;%s&quot;, sqlite3_errmsg(sqlite3Database));
}
</pre>
<p>Things are much simple here. We run the query, and if it&#x2019;s all okay, we store the affected rows and the last inserted row ID to the respective properties. In the <em>else</em> cases you see that we show on the debugger the error description, when the query cannot be executed and when the database can&#x2019;t be opened.</p>
<p>Finally, we need to free up the memory by releasing all used resources, and by closing the connection to database:</p>
<pre lang="objc">// Release the compiled statement from memory.
        sqlite3_finalize(compiledStatement);

    }

    // Close the database.
    sqlite3_close(sqlite3Database);
</pre>
<p>That was the last step needed to be performed in the method. Right below it&#x2019;s given in one piece, as all the if-else cases and the curly brackets become confusing enough:</p>
<pre lang="objc">-(void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable{
    // Create a sqlite object.
    sqlite3 *sqlite3Database;

    // Set the database file path.
    NSString *databasePath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];

    // Initialize the results array.
    if (self.arrResults != nil) {
        [self.arrResults removeAllObjects];
        self.arrResults = nil;
    }
    self.arrResults = [[NSMutableArray alloc] init];

    // Initialize the column names array.
    if (self.arrColumnNames != nil) {
        [self.arrColumnNames removeAllObjects];
        self.arrColumnNames = nil;
    }
    self.arrColumnNames = [[NSMutableArray alloc] init];


    // Open the database.
    BOOL openDatabaseResult = sqlite3_open([databasePath UTF8String], &amp;sqlite3Database);
    if(openDatabaseResult == SQLITE_OK) {
        // Declare a sqlite3_stmt object in which will be stored the query after having been compiled into a SQLite statement.
        sqlite3_stmt *compiledStatement;

        // Load all data from database to memory.
        BOOL prepareStatementResult = sqlite3_prepare_v2(sqlite3Database, query, -1, &amp;compiledStatement, NULL);
        if(prepareStatementResult == SQLITE_OK) {
            // Check if the query is non-executable.
            if (!queryExecutable){
                // In this case data must be loaded from the database.

                // Declare an array to keep the data for each fetched row.
                NSMutableArray *arrDataRow;

                // Loop through the results and add them to the results array row by row.
                while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                    // Initialize the mutable array that will contain the data of a fetched row.
                    arrDataRow = [[NSMutableArray alloc] init];

                    // Get the total number of columns.
                    int totalColumns = sqlite3_column_count(compiledStatement);

                    // Go through all columns and fetch each column data.
                    for (int i=0; i<totalcolumns; i++){ convert the column data to text (characters). char *dbdataaschars="(char" *)sqlite3_column_text(compiledstatement, i); if there are contents in currenct (field) then add them current row array. (dbdataaschars !="NULL)" { characters string. [arrdatarow addobject:[nsstring stringwithutf8string:dbdataaschars]]; } keep name. (self.arrcolumnnames.count dbdataaschars="(char" *)sqlite3_column_name(compiledstatement, [self.arrcolumnnames store each fetched results array, but first check is actually data. (arrdatarow.count> 0) {
                        [self.arrResults addObject:arrDataRow];
                    }
                }
            }
            else {
                // This is the case of an executable query (insert, update, ...).

                // Execute the query.
                BOOL executeQueryResults = sqlite3_step(compiledStatement);
                if (executeQueryResults == SQLITE_DONE) {
                    // Keep the affected rows.
                    self.affectedRows = sqlite3_changes(sqlite3Database);

                    // Keep the last inserted row ID.
                    self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
                }
                else {
                    // If could not execute the query show the error message on the debugger.
                    NSLog(@&quot;DB Error: %s&quot;, sqlite3_errmsg(sqlite3Database));
                }
            }
        }
        else {
            // In the database cannot be opened then show the error message on the debugger.
            NSLog(@&quot;%s&quot;, sqlite3_errmsg(sqlite3Database));
        }

        // Release the compiled statement from memory.
        sqlite3_finalize(compiledStatement);

    }

    // Close the database.
    sqlite3_close(sqlite3Database);
}
</totalcolumns;></pre>
<h2>Loading Data and Executing Queries</h2>
<p>Now that the core method of our class has been implemented, we have only left to make use of it. That&#x2019;s simple, as we just have to implement two new small, public methods: One for running <em>select</em> queries and loading data, and one for executing <em>insert</em>, <em>update</em> and <em>delete</em> queries.</p>
<p>Let&#x2019;s begin by declaring both of them. Open the <em>DBManager.h</em> file, and add the next two lines:</p>
<pre lang="objc">@interface DBManager : NSObject

...

-(NSArray *)loadDataFromDB:(NSString *)query;

-(void)executeQuery:(NSString *)query;

@end
</pre>
<p>Let&#x2019;s focus on the first method, named <em>loadDataFromDB:</em>. This method accepts as a parameter value the query we want to be executed as a <em>NSString</em> object. For example, such a valid string would be this: <em>&#x201C;select * from people where age &gt; 18&#x201D;</em>. The fetched result set is returned as an array, and according to what I said in the previous section, this is going to be a two-dimensional array. The first array represents the rows, while each sub-array represents the columns of each row. Having said all that, let&#x2019;s go back to the <em>DBManager.m</em> file, and let&#x2019;s implement it:</p>
<pre lang="objc">-(NSArray *)loadDataFromDB:(NSString *)query{    
    // Run the query and indicate that is not executable.
    // The query string is converted to a char* object.
    [self runQuery:[query UTF8String] isQueryExecutable:NO];

    // Returned the loaded results.
    return (NSArray *)self.arrResults;
}
</pre>
<p>As you see, it&#x2019;s just a matter of two lines. In the first line, we call the <em>runQuery:isQueryExecutable:</em> method and we convert the query to a C string object. At the same time, we specify that the query is not executable.</p>
<p>In the second line we return the <em>arrResults</em> array that contains the query results, casting it first to a <em>NSArray</em> object. It would be a bad idea to make the <em>arrResults</em> array public and allow apps to have direct access to it, as then the returned data could be potentially altered before it used.</p>
<p>Going to the <em>executeQuery:</em> method now, here&#x2019;s it its definition:</p>
<pre lang="objc">-(void)executeQuery:(NSString *)query{
    // Run the query and indicate that is executable.
    [self runQuery:[query UTF8String] isQueryExecutable:YES];
}
</pre>
<p>In this one, there is not a return value. However, the <em>affectedRows</em> property can be used to verify whether there were any changes or not after having executed a query.</p>
<h2>A Sample Database</h2>
<p>The database class is ready to be used, but how can we do that without having an actual database to test it? So, in this part I&#x2019;m going to show you how to create a new database on Terminal, how to create a new table and finally how to embed the database file to the Xcode project. If you&#x2019;re not used to work in a command line environment don&#x2019;t worry; you&#x2019;ll find out that doing so it&#x2019;s interesting, different, even amusing.</p>
<p>For the purpose of this example we won&#x2019;t create a complex database. On the contrary, we will create just one table, named <strong>peopleInfo</strong>, with the following fields:</p>
<ul>
<li><em>peopleInfoID</em>: An integer value, the primary key of the table.</li>
<li><em>firstname</em>: A text value.</li>
<li><em>lastname</em>: A text value.</li>
<li><em>age</em>: An integer value.</li>
</ul>
<p>Such a table is just fine to try out all the functionalities we want. Let&#x2019;s see everything in action now. Click on the Spotlight icon, and type the <em>Terminal</em> word in the textfield:</p>
<p><img loading="lazy" decoding="async" width="478" height="131" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_8_spotlight_terminal.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3789"></p>
<p>Once it gets spotted, hit the Return key on the keyboard, or click on its name with your mouse and the terminal window will appear. We are going to create a new database file named <strong>sampledb.sql</strong>. For the record, let me say that you can use any extension you would like for the file, or no extension at all. The most common extensions are:</p>
<ul>
<li>.sql</li>
<li>.sqlite</li>
<li>.db</li>
</ul>
<p>Personally, I like to give the .sql extension to my database files, but feel free to use anything that better suits to your preferences.</p>
<p>To create the above database, simply write the following in the terminal:</p>
<pre lang="objc">sqlite3 sampledb.sql
</pre>
<p>The database file will be created at once, and you&#x2019;ll enter into the SQLite command line environment. The command needed to create a new table is quite similar to other SQL databases or DBMSs, with some slight differences though. Here it is:</p>
<pre lang="objc">CREATE TABLE peopleInfo(peopleInfoID integer primary key, firstname text, lastname text, age integer);
</pre>
<p>Even though this tutorial has nothing to do with offering instructions on how to use the SQLite command line environment, I believe that it would be useful to mention just a couple of commands. These are the <em>.tables</em> and the <em>.schema TABLE_NAME</em>. The first one displays a listing with all the tables you&#x2019;ve created in a database. The second one displays the the <em>Create Table</em> command for the table specified by the <em>Table_Name</em> parameter. Notice that both commands are preceded by the dot point (.), and there&#x2019;s not a semicolon at the end of the commands. For clear SQL commands, you use no dot mark, but you add the semicolon.</p>
<p>To quit from the SQLite environment, just type:</p>
<pre lang="objc">.quit
</pre>
<p>That way you&#x2019;ll return back to the terminal environment. The next screenshot of my terminal synopsizes all the above:</p>
<p><img loading="lazy" decoding="async" width="600" height="319" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_9_sqlite_terminal_sample.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3790" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_9_sqlite_terminal_sample.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_9_sqlite_terminal_sample-564x300.jpg 564w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Our next task is to add the database file to the Xcode project. You have two options for doing that: </p>
<ul>
<li>Either open the Finder, locate the file, and then drag and drop to the Project Navigator on Xcode, or,</li>
<li>Go to Xcode, open the menu <strong>File &gt; Add Files to &#x201C;SQLite3DBSample&#x201D;&#x2026;</strong>, and then locate the file and click on the Add button.</li>
</ul>
<p>No matter which way you&#x2019;ll choose, make sure that the <em>Copy items into destination group&#x2019;s folder (if needed)</em> and the <em>SQLite3DBSample</em> target checkmarks are selected in the window that will appear before the database file gets added to the project.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_10_add_file_options.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3791" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_10_add_file_options.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_10_add_file_options-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<h2>Demo App Interface Setup</h2>
<p>In most of my tutorials, this part is usually one of the first things you read. However, due to the fact that at the previous sections we created the database class and the sample file, the setup of the interface for our demo app had to be waiting up to this point. In here, as you&#x2019;ve already assumed, we&#x2019;ll work in the Interface Builder, and we will add all those subviews needed to make the app working, just like the sample demonstrated at the beginning of the tutorial. Further than that, we&#x2019;ll add the necessary IBOutlet properties and IBAction methods that will make everything properly work.</p>
<p>On the Project Navigator, click on the <em>Main.storyboard</em> file and wait until it appears in the Interface Builder. As I said in the App Overview section, this is going to be a navigation based app, therefore select the View Controller scene and then go to the menu: <strong>Editor &gt; Embed In &gt; Navigation Controller</strong>. Instantly, a navigation controller will be added at the left side of the scene, and a new arrow will point from the navigation controller to the View Controller scene.</p>
<p><img loading="lazy" decoding="async" width="504" height="365" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_11_ib_navcontroller.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3792" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_11_ib_navcontroller.jpg 504w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_11_ib_navcontroller-414x300.jpg 414w" sizes="(max-width: 504px) 100vw, 504px"></p>
<p>Let&#x2019;s focus now on adding all the necessary subviews to the scene, and after having finished with that, we&#x2019;ll add one more scene (a new view controller) which we&#x2019;ll use to add new records to the database. Right next you are given all the subviews you need to drag from the Objects library to the scene, along with the attributes needed to be specified:</p>
<h3>UITableView</h3>
<ul>
<li><strong>Frame</strong>: X=0, Y=0, Width=320, Height=568</li>
</ul>
<h3>UITableViewCell</h3>
<p><em>Drag a table view cell in the table view to make it prototype</em><br>
* <strong>Row Height</strong>: 60<br>
* <strong>Style</strong>: Subtitle<br>
* <strong>Identifier</strong>: idCellRecord<br>
* <strong>Selection</strong>: None<br>
* <strong>Accessory</strong>: Detail Disclosure</p>
<h3>UIBarButtonItem</h3>
<ul>
<li>Add it to the right side of the navigation bar</li>
<li><strong>Identifier</strong>: Add</li>
<li><strong>Tint</strong>: Red=255, Green=128, Blue=0</li>
</ul>
<p>Besides all the above, select the <em>Navigation Item</em> and set the next two attributes:<br>
1. <strong>Title</strong>: SQLite 3 Demo<br>
2. <strong>Back Button</strong>: Go Back</p>
<p>These are all the subviews of the View Controller scene. Here&#x2019;s how it should look like:</p>
<p><img loading="lazy" decoding="async" width="277" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_12_ib_viewcontroller_scene.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3793" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_12_ib_viewcontroller_scene.jpg 277w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_12_ib_viewcontroller_scene-184x300.jpg 184w" sizes="(max-width: 277px) 100vw, 277px"></p>
<p>Now, from the Objects library take a <em>UIViewController</em> object and drop it to the canvas. For this view controller, we need to create a new class, so for the time being we&#x2019;ll just pause our work here.</p>
<p>Following the same way you did when you added the database class file to the project, add a new class of <em>UIViewController</em> kind. Specifically:</p>
<ol>
<li>Go to the menu: <strong>File &gt; New &gt; File&#x2026;</strong>.</li>
<li>As the template for the file, select the <strong>Objective-C class</strong> in the <strong>Cocoa Touch</strong> category, under the <strong>iOS</strong> section.</li>
<li>In the second step, make sure that in the <strong>Subclass of</strong> field there is the <strong>UIViewController</strong> value. If there is not, just type it. In the <strong>Class</strong> field, set the <strong>EditInfoViewController</strong> as the name for the new class, and then click on the Next button to proceed.</li>
<li>In the last step, make sure that the <em>SQLite3DBSample</em> is checked, and click on the Create button.</li>
</ol>
<p>Head back to the Interface Builder, and select the second, new scene. In the <strong>Utilities</strong> pane show the <strong>Identity Inspector</strong>, and in the <strong>Class</strong> field type the <strong>EditInfoViewController</strong> value. Immediately, the second view controller scene will turn into the Edit Info View Controller scene.</p>
<p>To connect the View Controller scene with the Edit Info View Controller scene, go to the Document Outline pane, Ctrl-Click on the View Controller scene object, and drag right onto the Edit Info View Controller object.</p>
<p><img loading="lazy" decoding="async" width="304" height="350" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_13_custom_segue.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3794" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_13_custom_segue.jpg 304w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_13_custom_segue-260x300.jpg 260w" sizes="(max-width: 304px) 100vw, 304px"></p>
<p>In the black popup window that appears (titled <em>Manual Segue</em>), select and click the <strong>Push</strong> option:</p>
<p><img loading="lazy" decoding="async" width="287" height="151" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_14_push_segue.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3795"></p>
<p>The two scenes will become connected, but there&#x2019;s still one last thing to do. Click on the circle of the connection line, and in the <strong>Attributes</strong> inspector set the <strong>idSegueEditInfo</strong> as the identifier value for the segue.</p>
<p><img loading="lazy" decoding="async" width="600" height="451" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_15_segue_identifier.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3796" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_15_segue_identifier.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_15_segue_identifier-399x300.jpg 399w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Now, we can add the necessary subviews here too:</p>
<h3>UITextField</h3>
<ul>
<li><strong>Frame</strong>: X=20, Y=93, Width=280, Height=30</li>
<li><strong>Placeholder</strong>: Type the first name&#x2026;</li>
<li><strong>Color</strong>: Red=255, Green=128, Blue=0</li>
<li><strong>Border Style</strong>: No border style</li>
<li><strong>Background</strong>: Red=217, Green=219, Blue=221</li>
<li><strong>Capitalization</strong>: Words</li>
<li><strong>Return Key</strong>: Done</li>
</ul>
<h3>UITextField</h3>
<ul>
<li><strong>Frame</strong>: X=20, Y=139, Width=280, Height=30</li>
<li><strong>Placeholder</strong>: Type the last name&#x2026;</li>
<li><strong>Color</strong>: Red=255, Green=128, Blue=0</li>
<li><strong>Border Style</strong>: No border style</li>
<li><strong>Background</strong>: Red=217, Green=219, Blue=221</li>
<li><strong>Capitalization</strong>: Words</li>
<li><strong>Return Key</strong>: Done</li>
</ul>
<h3>UITextField</h3>
<ul>
<li><strong>Frame</strong>: X=20, Y=186, Width=280, Height=30</li>
<li><strong>Placeholder</strong>: Type the age&#x2026;</li>
<li><strong>Color</strong>: Red=255, Green=128, Blue=0</li>
<li><strong>Border Style</strong>: No border style</li>
<li><strong>Background</strong>: Red=217, Green=219, Blue=221</li>
<li><strong>Capitalization</strong>: Words</li>
<li><strong>Return Key</strong>: Done</li>
<li><strong>Keyboard</strong>: Numbers and Punctuation</li>
</ul>
<h3>UIBarButtonItem</h3>
<ul>
<li>Add it to the right side of the navigation bar</li>
<li><strong>Identifier</strong>: Save</li>
<li><strong>Tint</strong>: Red=255, Green=128, Blue=0</li>
</ul>
<p>Also, edit the navigation item and set the <em>Edit Info</em> value as its title.</p>
<p>Here&#x2019;s how the second view controller should look like:</p>
<p><img loading="lazy" decoding="async" width="253" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_16_editinfoviewcontroller_scene.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3797" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_16_editinfoviewcontroller_scene.jpg 253w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_16_editinfoviewcontroller_scene-168x300.jpg 168w" sizes="(max-width: 253px) 100vw, 253px"></p>
<p>Let&#x2019;s see now what IBOutlet properties and IBActions are needed to be declared for the subviews we previously added. Starting from the View Controller scene, we want an IBOutlet property for the table view, so as we can display our data, and an IBAction method for the bar button item, which we&#x2019;ll use to perform the segue and transit to the EditInfoViewController view controller. Open the <em>ViewController.h</em> file, and add the next two declarations:</p>
<pre lang="objc">@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITableView *tblPeople;


- (IBAction)addNewRecord:(id)sender;

@end
</pre>
<p>Go back to the Interface builder and make the proper connections.</p>
<p>Next, for the Edit Info View Controller scene we&#x2019;ll need an IBOutlet property for each textfield, and an IBAction method for the save button. Similarly to the previous steps, open the <em>EditInfoViewController.h</em> file and declare them:</p>
<pre lang="objc">@interface EditInfoViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITextField *txtFirstname;

@property (weak, nonatomic) IBOutlet UITextField *txtLastname;

@property (weak, nonatomic) IBOutlet UITextField *txtAge;


- (IBAction)saveInfo:(id)sender;

@end
</pre>
<p>Finally, go to the Interface Builder once again and do the appropriate connections, as shown in the next figure:</p>
<p><img loading="lazy" decoding="async" width="600" height="473" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_17_iboutlet_connection.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3798" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t15_17_iboutlet_connection.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t15_17_iboutlet_connection-380x300.jpg 380w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Note that when you&#x2019;ll be viewing the <em>EditInfoViewController</em> view controller, the back button will appear to the navigation bar along with the Save button. To let it have the same color to the Save button you just need to go to the <em>EditInfoViewController.m</em> file, and to add the next line in the <em>viewDidLoad</em> method:</p>
<pre lang="objc">- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    // Set the navigation bar tint color.
    self.navigationController.navigationBar.tintColor = self.navigationItem.rightBarButtonItem.tintColor;

}
</pre>
<h2>Adding New Records</h2>
<p>Having the interface of the sample app prepared, we can go towards the implementation of our sample app where we&#x2019;ll try out our database class. As no data still exist in our database, the best point to start from would be to develop the feature of adding a new record. That requires work in both of our view controllers: In the <em>View Controller</em> class we should make the <em>Add (plus button)</em> functioning, so we can navigate to the next view controller. In the <em>Edit Info View Controller</em> class, we will get all values from textfields, and using an <em>insert</em> command, we&#x2019;ll add a new record to database.</p>
<p>Let&#x2019;s see everything in details. Go to the <em>ViewController.m</em> file, and straight ahead to the <em>addNewRecord:</em> IBAction method. Navigating to a new view controller using segues is easy, so the only thing we have to do here is to write just one line of code:</p>
<pre lang="objc">- (IBAction)addNewRecord:(id)sender {
    [self performSegueWithIdentifier:@&quot;idSegueEditInfo&quot; sender:self];
}
</pre>
<p>Focusing now our attention on the <em>EditInfoViewController</em> class, the first thing we should take care about is to dismiss the keyboard every time the Done button on it is tapped. To do so, we must implement one textfield delegate method, but first, we must adopt the respective protocol. So, open the <em>EditInfoViewController.h</em> file, and modify the header line as follows:</p>
<pre lang="objc">@interface EditInfoViewController : UIViewController <uitextfielddelegate>
</uitextfielddelegate></pre>
<p>Next, we must indicate that our class is the delegate of the textfields, and that can be done in two ways: Either to do it in Interface Builder, or to do it programmatically. The second is the way I prefer, as I think is much simpler. Open the <em>EditInfoViewController.m</em> file and go to the <em>viewDidLoad</em> method. In there add these three lines:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    // Make self the delegate of the textfields.
    self.txtFirstname.delegate = self;
    self.txtLastname.delegate = self;
    self.txtAge.delegate = self;
}
</pre>
<p>Now, we are ready to implement a simple delegate method and know when the Done button of the keyboard gets tapped. That method is the <em>textFieldShouldReturn:</em>, and in its implementation we&#x2019;ll perform just one task: We&#x2019;ll resign the textfield from first responder. Here it is:</p>
<pre lang="objc">-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
</pre>
<p>Time to work with the database. Go to the top of the file, and import our custom class:</p>
<pre lang="objc">#import &quot;DBManager.h&quot;
</pre>
<p>Now that the database class can be used, let&#x2019;s declare a private property to do so. Go to the private class section and add the next declaration:</p>
<pre lang="objc">@interface EditInfoViewController ()

@property (nonatomic, strong) DBManager *dbManager;

@end
</pre>
<p>Then, in the <em>viewDidLoad</em> method initialize it using the custom init method we implemented:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    // Initialize the dbManager object.
    self.dbManager = [[DBManager alloc] initWithDatabaseFilename:@&quot;sampledb.sql&quot;];

}
</pre>
<p>By initializing as shown above, upon the first run the database class will check if the <em>sampledb.sql</em> file exists or not in the documents directory, and it will copy it there if not found.</p>
<p>What we have left to do now is easy, but the most important part. Using all the textfield text values, we&#x2019;ll prepare an <em>insert</em> query and we&#x2019;ll execute it. To verify the outcome of the execution we&#x2019;ll output to the debugger either a success message, or the error message if any error occurs. Also, upon successful saving we&#x2019;ll display the number of the affected rows, so we&#x2019;ll manage to see if our class works as expected.</p>
<p>To do all that go to the <em>saveInfo:</em> IBAction method. Right next is given its implementation:</p>
<pre lang="objc">- (IBAction)saveInfo:(id)sender {
    // Prepare the query string.    
    NSString *query = [NSString stringWithFormat:@&quot;insert into peopleInfo values(null, &apos;%@&apos;, &apos;%@&apos;, %d)&quot;, self.txtFirstname.text, self.txtLastname.text, [self.txtAge.text intValue]];

    // Execute the query.
    [self.dbManager executeQuery:query];

    // If the query was successfully executed then pop the view controller.
    if (self.dbManager.affectedRows != 0) {
        NSLog(@&quot;Query was executed successfully. Affected rows = %d&quot;, self.dbManager.affectedRows);

        // Pop the view controller.
        [self.navigationController popViewControllerAnimated:YES];
    }
    else{
        NSLog(@&quot;Could not execute the query.&quot;);
    }
}
</pre>
<p>Notice that after having added a new record successfully, we also pop the view controller and return back to the <em>View Controller</em> one.</p>
<p>The app can be tested now for first time. Compile and run it, and try to add a new record. When you finish typing data, tap on the Save button and watch at the debugger. If you see a message similar to the next one, then congratulations, the database is working!</p>
<p><img loading="lazy" decoding="async" width="600" height="37" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_18_insert_record_sample.jpg" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3799"></p>
<h2>Loading and Displaying Records</h2>
<p>Now that we can successfully add records to the database, the most reasonable next step is to display them, so we&#x2019;ll work on the <em>View Controller</em> class. Summarizing what we have to do here, I would say that our job has two parts: The first one is to implement all the necessary, required table view methods so our loaded data from the database get listed properly on the table view. The second one is to create a <em>select</em> query, load our data and finally display them.</p>
<p>If you recall, when we did all the setup in the Interface Builder, we declared an IBOutlet property for the table view. Using it, we&#x2019;ll make the <em>View Controller</em> class both the delegate and datasource of it, but prior to that we must adopt two necessary protocols, the <em>UITableViewDelegate</em> and the <em>UITableViewDataSource</em>. As always, this will take place in the <em>ViewController.h</em> file, where we&#x2019;ll modify the <em>@interface</em> header line as follows:</p>
<pre lang="objc">@interface ViewController : UIViewController <uitableviewdelegate, uitableviewdatasource>
</uitableviewdelegate,></pre>
<p>Next, in the <em>ViewController.m</em> file and in the <em>viewDidLoad</em> method we just have to write these:</p>
<pre lang="objc">- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Make self the delegate and datasource of the table view.
    self.tblPeople.delegate = self;
    self.tblPeople.dataSource = self;
}
</pre>
<p>Now, let&#x2019;s get started by loading the data from the database. To do so, we need three things:</p>
<ol>
<li>To declare and initialize a <em>DBManager</em> property.</li>
<li>To declare and array for storing the returned data.</li>
<li>A private method to do the job.</li>
</ol>
<p>Go to the private section of the class, and declare the next two properties, and one private method:</p>
<pre lang="objc">@interface ViewController ()

@property (nonatomic, strong) DBManager *dbManager;

@property (nonatomic, strong) NSArray *arrPeopleInfo;


-(void)loadData;

@end
</pre>
<p>Don&#x2019;t worry if Xcode is showing an error. We just need to import our database class header:</p>
<pre lang="objc">#import &quot;DBManager.h&quot;
</pre>
<p>Now, as we exactly did in the <em>EditInfoViewController</em> class, we&#x2019;ll initialize the database property here as well:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    // Initialize the dbManager property.
    self.dbManager = [[DBManager alloc] initWithDatabaseFilename:@&quot;sampledb.sql&quot;];

}
</pre>
<p>Our next task is to implement the <em>loadData</em> method, and prepare the <em>select</em> query. Let&#x2019;s see it first:</p>
<pre lang="objc">-(void)loadData{
    // Form the query.
    NSString *query = @&quot;select * from peopleInfo&quot;;

    // Get the results.
    if (self.arrPeopleInfo != nil) {
        self.arrPeopleInfo = nil;
    }
    self.arrPeopleInfo = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];

    // Reload the table view.
    [self.tblPeople reloadData];
}
</pre>
<p>Three things happen here: At first, the query string is prepared, and as you see, is a simple <em>select</em> statement. Then, the <em>arrPeopleInfo</em> array gets initialized, and upon its initialization we call the <em>loadDataFromDB:</em> method of the <em>dbManager</em> object. Once the data has been fetched and returned, we reload the table view to display it. For the time being the last line will do nothing, but after we have had our table view ready, it will be working just fine.</p>
<p>Loading data is as simple as you see in the previous code snippet. Having done so, enables us to move ahead and work with the table view. Note that based on the <em>arrPeopleInfo</em> array, we will be able to define the total rows of the table view.</p>
<p>Regarding the table view methods, let&#x2019;s get started from the easy ones:</p>
<pre lang="objc">
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrPeopleInfo.count;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60.0;
}
</pre>
<p>In the first one, we tell our table view that we want to have just one section. With the second one, we specify the total number of rows displayed in the table view. Actually, this method will return as many rows as those existing in the result set that will be loaded from the database. Finally, with the third one we set each row&#x2019;s height to 60.0 points.</p>
<p>To display a row&#x2019;s data, we&#x2019;ll use the <em>tableView:cellForRowAtIndexPath:</em> method. In it, initially we&#x2019;ll dequeue the prototype cell we created in the Interface Builder. Then, making use of the <em>arrColumnNames</em> array of the <em>dbManager</em> property we&#x2019;ll define the index of each column (field) in the sub-array for the current index of the <em>arrPeopleInfo</em> array. Finally, we&#x2019;ll get the actual data and assign it to the <em>textLabel</em> and <em>detailTextLabel</em> labels of the cell. Here&#x2019;s the implementation:</p>
<pre lang="objc">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // Dequeue the cell.
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@&quot;idCellRecord&quot; forIndexPath:indexPath];

    NSInteger indexOfFirstname = [self.dbManager.arrColumnNames indexOfObject:@&quot;firstname&quot;];
    NSInteger indexOfLastname = [self.dbManager.arrColumnNames indexOfObject:@&quot;lastname&quot;];
    NSInteger indexOfAge = [self.dbManager.arrColumnNames indexOfObject:@&quot;age&quot;];

    // Set the loaded data to the appropriate cell labels.
    cell.textLabel.text = [NSString stringWithFormat:@&quot;%@ %@&quot;, [[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:indexOfFirstname], [[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:indexOfLastname]];

    cell.detailTextLabel.text = [NSString stringWithFormat:@&quot;Age: %@&quot;, [[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:indexOfAge]];

    return cell;
}
</pre>
<p>Notice that instead of using the <em>indexOfFirstname</em>, <em>indexOfLastname</em> and <em>indexOfAge</em> variables for accessing the proper data, we could have used the index number for each field directly. For example, instead of writing this:</p>
<pre lang="objc">cell.detailTextLabel.text = [NSString stringWithFormat:@&quot;Age: %@&quot;, [[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:indexOfAge]];
</pre>
<p>we could just have written this:</p>
<pre lang="objc">cell.detailTextLabel.text = [NSString stringWithFormat:@&quot;Age: %@&quot;, [[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:3]];
</pre>
<p>Using or not the column names array is totally up to you, and I used it here just for demonstrative reasons. I just wanted to make clear how you can specify the index of a field programmatically, even though our example is quite simple and it is not necessary to do this.</p>
<p>So, it seems that we&#x2019;ve finished taking all the proper actions for loading the data and showing it to the table view. However, if you run the app now, you&#x2019;ll see no data displayed at all. That&#x2019;s because of a simple reason: We didn&#x2019;t call the <em>loadData</em> method anywhere. So, go to the <em>viewDidLoad</em> method and add the next line:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    // Load the data.
    [self loadData];
}
</pre>
<p>Run the app once again. This time, the records you added in the previous step are shown in the table view. That&#x2019;s great.</p>
<p>Before we consider this section as finished, there&#x2019;s one more detail we should take care about. You&#x2019;ll definitely notice that when adding a new record and then tapping on the Save button, the record is saved and you&#x2019;re transferred back to the <em>View Controller</em> view controller, but the table view doesn&#x2019;t get updated with the new data, unless you re-launch the app. That&#x2019;s because for the time being the <em>View Controller</em> view controller cannot know whether new data have been added to the database after the <em>Edit Info View Controller</em> view controller has popped from the navigation stack. To workaround this, we must create a protocol in the <em>EditInfoViewController</em> class, declare a delegate method to be used for notifying when a new record has been added, and adopt that protocol to the <em>ViewController</em> class.</p>
<p>Let&#x2019;s give life to all the above. Start by opening the <em>EditInfoViewController.h</em> file. At the top of it, add the next code fragment:</p>
<pre lang="objc">@protocol EditInfoViewControllerDelegate

-(void)editingInfoWasFinished;

@end
</pre>
<p>Next, in the interface right below, add a declaration for the delegate property:</p>
<pre lang="objc">@interface EditInfoViewController : UIViewController <uitextfielddelegate>

...

@property (nonatomic, strong) id<editinfoviewcontrollerdelegate> delegate;

@end
</editinfoviewcontrollerdelegate></uitextfielddelegate></pre>
<p>Finally, go to the <em>saveInfo:</em> IBAction method and modify it, so the delegate method is called before popping the view controller. Right next, you are given that method updated:</p>
<pre lang="objc">- (IBAction)saveInfo:(id)sender {
    // Prepare the query string.
    NSString *query = [NSString stringWithFormat:@&quot;insert into peopleInfo values(null, &apos;%@&apos;, &apos;%@&apos;, %d)&quot;, self.txtFirstname.text, self.txtLastname.text, [self.txtAge.text intValue]];

    // Execute the query.
    [self.dbManager executeQuery:query];

    // If the query was successfully executed then pop the view controller.
    if (self.dbManager.affectedRows != 0) {
        NSLog(@&quot;Query was executed successfully. Affected rows = %d&quot;, self.dbManager.affectedRows);

        // Inform the delegate that the editing was finished.
        [self.delegate editingInfoWasFinished];

        // Pop the view controller.
        [self.navigationController popViewControllerAnimated:YES];
    }
    else{
        NSLog(@&quot;Could not execute the query.&quot;);
    }
}
</pre>
<p>With the above three steps, the <em>EditInfoViewController</em> will notify the delegate class every time a new save action occurs.</p>
<p>Let&#x2019;s go now to the <em>ViewController.h</em> file. Go to the top of it, and make the next import:</p>
<pre lang="objc">#import &quot;EditInfoViewController.h&quot;
</pre>
<p>Then, modify the <em>@interface</em> header a bit:</p>
<pre lang="objc">@interface ViewController : UIViewController <uitableviewdelegate, uitableviewdatasource, editinfoviewcontrollerdelegate>
</uitableviewdelegate,></pre>
<p>As you see, now we are adopting the <em>EditInfoViewControllerDelegate</em> protocol, so the only thing we have left is to implement the delegate method. Go to the <em>ViewController.m</em> file, and add the next code segment:</p>
<pre lang="objc">-(void)editingInfoWasFinished{
    // Reload the data.
    [self loadData];
}
</pre>
<p>As you may have expected, the only thing we do is to load our data once again.</p>
<p>However, nothing is going to happen until we make the <em>ViewController</em> class the delegate of the <em>EditInfoViewController</em> one. We&#x2019;ll do that in the <em>prepareForSegue:sender:</em> method, which is called before the segue is performed. Here it is:</p>
<pre lang="objc">-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    EditInfoViewController *editInfoViewController = [segue destinationViewController];
    editInfoViewController.delegate = self;
}
</pre>
<p>If you run the app, you&#x2019;ll see that is working and behaving much better now. When adding new records, they immediately appear in the table view after having tapped on the Save button.</p>
<h2>Editing a Record</h2>
<p>Our sample app will be much better if we add support for editing and deleting records, apart from just adding new and loading existing ones. Also, that way we&#x2019;ll see in action how the <em>update</em> and <em>delete</em> queries work, and we&#x2019;ll test our database class even more.</p>
<p>In this section we&#x2019;ll see how to edit a record. Running the app and looking at the table view, you notice that we have added a detail disclosure indicator on the prototype cell. That&#x2019;s what we&#x2019;ll use to edit a record matching to the respective row. The actual editing will take place in the <em>EditInfoViewController</em> class, which we&#x2019;ll modify a little bit, so when saving it will either execute an <em>insert</em> or an <em>update</em> query.</p>
<p>The most important part of the underlying logic is the existence of a public int property in the <em>EditInfoViewController</em> class, in which the edited record&#x2019;s ID will be assigned. When saving, that property will be used to specify the exact data that should be updated. However, in case of adding a new record, we&#x2019;ll set the &#x2212;1 value to this property, indicating that way we want to run an <em>insert</em> query, not an update. Lastly, when the <em>EditInfoViewController</em> view controller is appeared to edit a record, the data for that specific record will be loaded and assigned to the textfields.</p>
<p>If all the above seem confusing, don&#x2019;t worry. Come along to perform some simple steps, and everything will become crystal clear.</p>
<p>Let&#x2019;s get started from the <em>EditInfoViewController.h</em> file, where we should declare the public int property:</p>
<pre lang="objc">@interface EditInfoViewController : UIViewController <uitextfielddelegate>

...

@property (nonatomic) int recordIDToEdit;

@end
</uitextfielddelegate></pre>
<p>Now, open the <em>EditInfoViewController.m</em> file and declare a private method which will be used to load the edited data. Go to the private section of the class, and add the next line:</p>
<pre lang="objc">@interface EditInfoViewController ()

...

-(void)loadInfoToEdit;

@end
</pre>
<p>Now, let&#x2019;s implement it:</p>
<pre lang="objc">-(void)loadInfoToEdit{
    // Create the query.
    NSString *query = [NSString stringWithFormat:@&quot;select * from peopleInfo where peopleInfoID=%d&quot;, self.recordIDToEdit];

    // Load the relevant data.
    NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];

    // Set the loaded data to the textfields.
    self.txtFirstname.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@&quot;firstname&quot;]];
    self.txtLastname.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@&quot;lastname&quot;]];
    self.txtAge.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@&quot;age&quot;]];
}
</pre>
<p>Everything is quite straightforward here. At first, we form the query. As you notice, it&#x2019;s the first time we have a <em>where</em> clause. Then, we get the data from the database and assign the appropriate values to the textfields.</p>
<p>The above method won&#x2019;t work if we don&#x2019;t call it, so go to the <em>viewDidLoad</em> method and make a conditional call:</p>
<pre lang="objc">- (void)viewDidLoad
{
    ...

    // Check if should load specific record for editing.
    if (self.recordIDToEdit != -1) {
        // Load the record with the specific ID from the database.
        [self loadInfoToEdit];
    }
}
</pre>
<p>Great, but we&#x2019;ve left one more step in this class: To modify the <em>saveInfo:</em> IBAction method and make it update an existing record instead of just inserting new records to the database. Right below you&#x2019;re given the method implemented in its final form. Notice how using the <em>recordIDToEdit</em> property we specify the query type:</p>
<pre lang="objc">- (IBAction)saveInfo:(id)sender {
    // Prepare the query string.
    // If the recordIDToEdit property has value other than -1, then create an update query. Otherwise create an insert query.
    NSString *query;
    if (self.recordIDToEdit == -1) {
        query = [NSString stringWithFormat:@&quot;insert into peopleInfo values(null, &apos;%@&apos;, &apos;%@&apos;, %d)&quot;, self.txtFirstname.text, self.txtLastname.text, [self.txtAge.text intValue]];
    }
    else{
        query = [NSString stringWithFormat:@&quot;update peopleInfo set firstname=&apos;%@&apos;, lastname=&apos;%@&apos;, age=%d where peopleInfoID=%d&quot;, self.txtFirstname.text, self.txtLastname.text, self.txtAge.text.intValue, self.recordIDToEdit];
    }


    // Execute the query.
    [self.dbManager executeQuery:query];

    // If the query was successfully executed then pop the view controller.
    if (self.dbManager.affectedRows != 0) {
        NSLog(@&quot;Query was executed successfully. Affected rows = %d&quot;, self.dbManager.affectedRows);

        // Inform the delegate that the editing was finished.
        [self.delegate editingInfoWasFinished];

        // Pop the view controller.
        [self.navigationController popViewControllerAnimated:YES];
    }
    else{
        NSLog(@&quot;Could not execute the query.&quot;);
    }
}
</pre>
<p>Our job in the <em>EditInfoViewController</em> class is over. However, that was just the half part of what we should do. We must go to the <em>ViewController</em> class now and make the detail disclosure button of the cells functional.</p>
<p>To detect tappings on the detail disclosure buttons, <em>UITableViewDelegate</em> protocol provides the <em>tableView:accessoryButtonTappedForRowWithIndexPath:</em> delegate method. We are going to implement it, and inside its body we&#x2019;ll do two simple tasks:</p>
<ol>
<li>We will specify the record ID that&#x2019;s about to be edited.</li>
<li>We&#x2019;ll perform the segue so the <em>EditInfoViewController</em> view controller gets pushed to the navigation stack and make us able to edit.</li>
</ol>
<p>We&#x2019;ll get started by declaring a private property to the <em>ViewController</em> class similar to the <em>recordIDToEdit</em>, because we&#x2019;ll need a way to keep the record ID matching to the row of the tapped button. So, go to the private section of the interface, and do so:</p>
<pre lang="objc">@interface ViewController ()

...

@property (nonatomic) int recordIDToEdit;

@end
</pre>
<p>With the above private property declared, we can proceed to the <em>tableView:accessoryButtonTappedForRowWithIndexPath:</em> implementation:</p>
<pre lang="objc">-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    // Get the record ID of the selected name and set it to the recordIDToEdit property.
    self.recordIDToEdit = [[[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:0] intValue];

    // Perform the segue.
    [self performSegueWithIdentifier:@&quot;idSegueEditInfo&quot; sender:self];
}
</pre>
<p>Easy enough, but now we must tell the <em>EditInfoViewController</em> class what the record ID we want to edit is. This should take place before the segue is performed, so go to the <em>prepareForSegue:sender:</em> and add just one line:</p>
<pre lang="objc">-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    ...
    editInfoViewController.recordIDToEdit = self.recordIDToEdit;
}
</pre>
<p>We are almost finished. The only issue that we&#x2019;re still having, is that we haven&#x2019;t specified the value of the <em>recordIDToEdit</em> property when we&#x2019;re about to add a new record. That can be easily fixed, as we just have to go to the <em>addNewRecord:</em> IBAction method definition, and modify it as follows:</p>
<pre lang="objc">- (IBAction)addNewRecord:(id)sender {
    // Before performing the segue, set the -1 value to the recordIDToEdit. That way we&apos;ll indicate that we want to add a new record and not to edit an existing one.
    self.recordIDToEdit = -1;

    // Perform the segue.
    [self performSegueWithIdentifier:@&quot;idSegueEditInfo&quot; sender:self];
}
</pre>
<p>Everything is ready now. Feel free to run the app once again, and then try to edit one or more of any existing records. As it seems, our database class perfectly works and our sample app gains more features.</p>
<h2>Deleting a Record</h2>
<p>Now that we can insert, load and update records, let&#x2019;s make our app able to delete them as well. To delete a record, we&#x2019;ll use the built-in table view functionality, where by swiping on a row towards left, the delete button is appeared.</p>
<p>To do that possible, we must implement the <em>tableView:commitEditingStyle:forRowAtIndexPath:</em> table view method. In it, if the editing style is a delete style, we&#x2019;ll execute a <em>delete</em> query, and then we&#x2019;ll reload the data. As simple as that, and the record deletion will be ready. Let&#x2019;s see it:</p>
<pre lang="objc">-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the selected record.
        // Find the record ID.
        int recordIDToDelete = [[[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:0] intValue];

        // Prepare the query.
        NSString *query = [NSString stringWithFormat:@&quot;delete from peopleInfo where peopleInfoID=%d&quot;, recordIDToDelete];

        // Execute the query.
        [self.dbManager executeQuery:query];

        // Reload the table view.
        [self loadData];
    }
}
</pre>
<p>At first, we set the ID of the record to be deleted. Then, we compose the query string appropriately, we execute it using the <em>executeQuery:</em> method of our database class, and finally we load the data once again. That way, every time the delete button of a row is tapped, the respective record on the database will be permanently removed.</p>
<p>If you want now give the app one more try, and see how it works. All the basic features are now implemented and fully functional.</p>
<h2>Compile and Run the App</h2>
<p>This section exists in almost every tutorial in case you are one of those guys who wait to arrive at the finish point, and then run and test the app. Well, we&#x2019;re almost at the end of our mission, so if you still haven&#x2019;t run it, do it now. Begin by adding a new record, and then save it. Next, try to edit it, and finally delete it. Add as many records as you want and generally do whatever you want for testing both the sample app and the database class. Even more, add any extra features you may think of and build more complex queries.</p>
<p>Right next it&#x2019;s demonstrated the animated graphic presented at the beginning of the tutorial too:</p>
<p><img loading="lazy" decoding="async" width="313" height="587" src="http://www.appcoda.com/wp-content/uploads/2014/06/t15_19_sample.gif" alt="How to Use SQLite to Manage Data in iOS Apps" class="aligncenter size-full wp-image-3800"></p>
<h2>Summary</h2>
<p>I&#x2019;ve always believed that working with databases is the best possible solution when dealing with data, and having relevant tools or libraries ready for use is a must for every developer. SQLite might not be as powerful as other databases or database management systems, however is light and maybe the most suitable solution for a mobile platform. The class we developed in this tutorial is not set of stone, so keep in mind that you can change it and evolve it at any time and in any possible way that serves you. With it, I just wanted to provide you with a working, suitable for the most cases, reusable component, which could potentially have double results: Both to teach you the basics of SQLite, and to get you out of the hassle of developing other custom data handling solutions. That said, I truly hope you have learned and earned something new by this tutorial, and as always let me know your thoughts or questions. Until next time, I wish an easy, bug-free programming to all!</p>
<p>For your reference, you can <a href="https://dl.dropboxusercontent.com/u/2857188/SQLite3DBSample.zip?ref=appcoda.com">download the complete Xcode project from here</a>.</p>

<!--kg-card-end: html-->
]]></content:encoded></item><item><title><![CDATA[Using iAd to Display Banner Ad in Your App]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>So, you are about to start developing the next super app, you have everything planned and designed, but there&#x2019;s still one last thing you haven&#x2019;t made your mind up about; how to make some earnings out of it! Well, there are two options apart from offering</p>]]></description><link>https://www.appcoda.com/ios-iad-introduction/</link><guid isPermaLink="false">66612a0f166d3c03cf011377</guid><category><![CDATA[iOS Programming]]></category><category><![CDATA[Objective C]]></category><dc:creator><![CDATA[Gabriel Theodoropoulos]]></dc:creator><pubDate>Tue, 17 Jun 2014 01:18:09 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2014/06/iad-featured.jpg" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://www.appcoda.com/content/images/wordpress/2014/06/iad-featured.jpg" alt="Using iAd to Display Banner Ad in Your App"><p>So, you are about to start developing the next super app, you have everything planned and designed, but there&#x2019;s still one last thing you haven&#x2019;t made your mind up about; how to make some earnings out of it! Well, there are two options apart from offering it completely free: Either to make it a paid app where your potentials users should pay to download it, or make it a free app, add some advertisements, and earn a revenue from the ads.</p>
<p>Today&#x2019;s trends show that it&#x2019;s more possible for users to download free apps, instead of paid ones. They will pay for an app if it really worths it, or if it&#x2019;s super famous and have received good rating. So, having that in mind, you decide to make your app a free one, and integrate advertisements in it. To do so, you have various services to pick from in order to display ads, and one of them is the iAd Network provided by Apple. Undoubtably, you have already concluded even from the tutorial&#x2019;s title that the today&#x2019;s topic is about how to use iAd advertisements, but before we see all in action let&#x2019;s see some introductory stuff.</p>
<p>Deciding about the kind of your application (paid or free) before starting the actual implementation is really important, as it affects your work directly. For paid apps, there&#x2019;s no need to do anything particular, however for free apps it&#x2019;s necessary to define where the ads will appear, and setup your interface accordingly. Speaking of position, ads should be placed either to the top or the bottom of your view controller. If your app does not contain a tab bar, then ads should be placed at the bottom of the screen, otherwise at the top. Note that if you display ads anywhere else in the view, then the Human Interface Guidelines are breached and Apple will reject it with no second thought.</p>
<p>Besides all the above regarding the positioning of the ads, there are a couple more rules you should have in mind. Firstly, don&#x2019;t expect ads to be always available. Various network or server-side problems may cause troubles in ad serving, and it&#x2019;s your duty to take care so no ugly empty space appears when no ads are there for you. It&#x2019;s considered as a good idea to show another meaningful view when no ads exist. Actually, it&#x2019;s totally up to your app design whether you should display another view instead of the ad banner or not, and what kind of view this should be.</p>
<p>Also, ad banners should not be obscured by other view controllers all the time. You have to make sure that they will appear in the most viewable view controller, the one that users will spend the most of their time when working with the app, and maximize that way the possibility for your ads to get tapped and earn some money.</p>
<p>Regarding the revenue, both Apple and developers benefit when users tap on advertisements. Actually, the developer&#x2019;s cut is equal to the 70% percent of the revenue, while the rest 30% is held by Apple as a commission for offering you the iAd Network services. The same split applies to paid apps too.</p>
<p>It&#x2019;s quite common for sole developers and companies to follow another approach, to create two versions of the same app. The first version, the paid, is the full-featured one. The second version is free, but it doesn&#x2019;t contain all the features that the paid version ships. That free version, also called Lite version, can have advertisements and beyond the revenue you may earn from them, you can also count on extra revenue if users like the app and buy the paid version. Remember that you should never add advertisements in paid apps. Even if Apple allows that to happen, and I seriously doubt about that, you&#x2019;ll receive the worst critics and ratings, as users don&#x2019;t pay to see ads.</p>
<p>In the next sections of the tutorial we&#x2019;ll implement as always a sample app, and through this you&#x2019;ll learn how to integrate ads provided by Apple into your projects. If you are new to this, you&#x2019;ll find out that using ads is a super-easy process. So, keep reading and discover how all this new great stuff works!</p>
<h2>App Overview</h2>
<p>As always, our tutorial will be based on the creation of a sample app. In the one we will start developing right next, we will see how to integrate iAd advertisements and display ad banners within a few steps. More specifically, we&#x2019;ll do the following:</p>
<ul>
<li>We will add an ad banner at the bottom side of the view. This will be the container in which the ads will be displayed if available. If there are no available ads, then we&#x2019;ll hide it until we have something to show.</li>
<li>Generally speaking, a modal full-screen view shows up when tapping on an advertisement, covering everything else behind it. In such cases, any critical or important tasks regarding especially visual updates must be paused or stopped, and get restarted after the ad has been closed. To demonstrate how this can be managed, we&#x2019;ll use a timer to count the seconds that the user is viewing the default view controller&#x2019;s view, and a label to display a message containing the timer&#x2019;s value. When an ad gets tapped, we&#x2019;ll stop counting, and we&#x2019;ll restart doing so when it&#x2019;s closed again.</li>
</ul>
<p>Also, in this tutorial we are going to use an extra framework, the <strong>iAd Framework</strong>. Without it, it&#x2019;s not possible to display and handle iAd advertisements.</p>
<p>The next figure illustrates how the app of this tutorial will look like:</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/06/t14_11_final_sample.jpg" alt="Using iAd to Display Banner Ad in Your App" class="aligncenter size-full wp-image-3741" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t14_11_final_sample.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/06/t14_11_final_sample-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<h2>Project Creation</h2>
<p>Let&#x2019;s begin by creating a new project for the sample app. Launch Xcode and in the Welcome window select the respective option, as shown in the next figure:</p>
<p><img loading="lazy" decoding="async" width="600" height="352" src="http://www.appcoda.com/wp-content/uploads/2014/06/t14_1_xcode_welcome.jpg" alt="Using iAd to Display Banner Ad in Your App" class="aligncenter size-full wp-image-3731" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t14_1_xcode_welcome.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t14_1_xcode_welcome-511x300.jpg 511w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>In the guide that appears, select the <strong>Single View Application</strong> template, in the <strong>Application</strong> category under the <strong>iOS</strong> section:</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/06/t14_2_template1.jpg" alt="Using iAd to Display Banner Ad in Your App" class="aligncenter size-full wp-image-3732" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t14_2_template1.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t14_2_template1-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Click Next, and in the <strong>Product Name</strong> field set the <strong>iAdDemo</strong> as the project&#x2019;s name. Also, make sure that the <strong>iPhone</strong> option is the selected one in the <strong>Devices</strong> menu. Leave the rest as it is, and proceed:</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/06/t14_3_template2.jpg" alt="Using iAd to Display Banner Ad in Your App" class="aligncenter size-full wp-image-3733" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t14_3_template2.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t14_3_template2-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>In the last step of the guide select a directory to save the project and click Create.</p>
<h2>Interface Configuration</h2>
<p>Now that we have an empty project on our hands, let&#x2019;s begin working on the interface of the app. Click on the <em>Main.storyboard</em> file to let Interface Builder appear. Below you are given all the subviews along with their attributes that you should add, so the final outcome of our work in this section is similar to the app figure illustrated previously. Note that you could skip some of the subviews that will be described next if you just want to focus just on the ad banner.</p>
<h3><strong>UILabel</strong></h3>
<ol>
<li><strong>Frame</strong>: X=20, Y=60, Width=280, Height=40</li>
<li><strong>Text</strong>: <em>iAd Integration</em></li>
<li><strong>Font</strong>: Avenir Black, 24.0pt</li>
<li><strong>Text Alignment</strong>: Center</li>
</ol>
<h3><strong>UILabel</strong></h3>
<ol>
<li><strong>Frame</strong>: X=20, Y=108, Width=280, Height=21</li>
<li><strong>Text</strong>: <em>by Appcoda</em></li>
<li><strong>Font</strong>: Avenir Medium Oblique, 17.0pt</li>
<li><strong>Text Alignment</strong>: Center</li>
<li><strong>Text Color</strong>: Red=255, Green=128, Blue=0</li>
</ol>
<h3><strong>UILabel</strong></h3>
<ol>
<li><strong>Frame</strong>: X=20, Y=360, Width=280, Height=40</li>
<li><strong>Text</strong>: None</li>
<li><strong>Font</strong>: Noteworthy Light, 15.0pt</li>
<li><strong>Text Alignment</strong>: Center</li>
<li><strong>Text Color</strong>: Light Gray</li>
</ol>
<h3><strong>UILabel</strong></h3>
<ol>
<li><strong>Frame</strong>: X=0, Y=518, Width=320, Height=50</li>
<li><strong>Text</strong>: <em>Ad banner will appear here</em></li>
<li><strong>Font</strong>: Avenir Medium, 14.0pt</li>
<li><strong>Text Alignment</strong>: Center</li>
<li><strong>Text Color</strong>: White</li>
<li><strong>Background Color</strong>: Red=255, Green=128, Blue=0</li>
</ol>
<h3><strong>ADBannerView</strong></h3>
<ol>
<li><strong>Frame</strong>: X=0, Y=518, Width=320, Height=50</li>
</ol>
<p>After adding all the above subviews and setting their attributes as shown, your interface should look like this:</p>
<p><img loading="lazy" decoding="async" width="253" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/06/t14_4_ib_sample.jpg" alt="Using iAd to Display Banner Ad in Your App" class="aligncenter size-full wp-image-3734" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t14_4_ib_sample.jpg 253w, https://www.appcoda.com/content/images/wordpress/2014/06/t14_4_ib_sample-168x300.jpg 168w" sizes="(max-width: 253px) 100vw, 253px"></p>
<p>It&#x2019;s necessary to create and connect two IBOutlet properties now. The first one regards the ad banner view, while the second one will be connected to the label that contains no text. In this label we&#x2019;ll display later the time counter value. Open the <em>ViewController.h</em> file, and the next two lines:</p>
<pre lang="objc">@interface ViewController : UIViewController <adbannerviewdelegate>

@property (weak, nonatomic) IBOutlet ADBannerView *adBanner;

@property (weak, nonatomic) IBOutlet UILabel *lblTimerMessage;

@end
</adbannerviewdelegate></pre>
<p>At this point Xcode will issue an error and some warnings. That&#x2019;s because we haven&#x2019;t added the iAd framework yet, and we haven&#x2019;t included the appropriate library on our file. Let&#x2019;s fix everything and let&#x2019;s start by adding the framework. On the Project Navigator, click on the <strong>iAdDemo</strong> project, and then in the <strong>General</strong> tab.</p>
<p><img loading="lazy" decoding="async" width="560" height="86" src="http://www.appcoda.com/wp-content/uploads/2014/06/t14_5_general_tab.jpg" alt="Using iAd to Display Banner Ad in Your App" class="aligncenter size-full wp-image-3735"></p>
<p>Next, at the bottom side of the screen, under the <strong>Linked Frameworks and Libraries</strong> section, click on the plus icon to add the new framework. In the new window that appears, start typing the text: &#x201C;iAd Framework&#x201D; and Xcode will immediately suggest it. Select it and then click on the Add button:</p>
<p><img loading="lazy" decoding="async" width="400" height="460" src="http://www.appcoda.com/wp-content/uploads/2014/06/t14_7_add_framework.jpg" alt="Using iAd to Display Banner Ad in Your App" class="aligncenter size-full wp-image-3737" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t14_7_add_framework.jpg 400w, https://www.appcoda.com/content/images/wordpress/2014/06/t14_7_add_framework-260x300.jpg 260w" sizes="(max-width: 400px) 100vw, 400px"></p>
<p>Now head back to the <em>ViewController.h</em> file, and import the next library:</p>
<pre lang="objc">#import <iad iad.h>
</iad></pre>
<p>With that, Xcode stops displaying any error and warnings. Finally, our class must adopt the ad banner view protocol, so we can access all the necessary delegate methods. Modify the interface header line as follows:</p>
<pre lang="objc">@interface ViewController : UIViewController <adbannerviewdelegate>
</adbannerviewdelegate></pre>
<p>As a last step, the two IBOutlet properties must be connected to the appropriate subviews. Open the <em>Main.storyboard</em> file, and connect the <em>adBanner</em> property to the ad banner view, and the <em>lblTimerMessage</em> label to the textless label view.</p>
<p><img loading="lazy" decoding="async" width="600" height="546" src="http://www.appcoda.com/wp-content/uploads/2014/06/t14_8_ib_connect.jpg" alt="Using iAd to Display Banner Ad in Your App" class="aligncenter size-full wp-image-3738" srcset="https://www.appcoda.com/content/images/wordpress/2014/06/t14_8_ib_connect.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/06/t14_8_ib_connect-329x300.jpg 329w" sizes="(max-width: 600px) 100vw, 600px"></p>
<h2>iAd Integration</h2>
<p>By adding the ad banner view to the interface and by also adding the iAd framework into the project, advertisements are already able to be delivered to the app. However, no handling is possible yet, therefore our goal here is to take all that actions that will make the ad banner management feasible.</p>
<p>The iAd framework provides several delegate methods for managing ads. These allow us to know when an ad is about to be shown or it has already been shown, when a failure occurs and no more ads can be served, and finally when the user taps on an ad to view it on full-screen mode or the modal ad view gets dismissed. Besides all that, you should always have in mind that ads are not delivered right away. Therefore, until the first ad is ready to be shown, the ad banner must not be visible. It should also become hidden when the iAd Network stops serving ads for some reason.</p>
<p>Diving into code now, initially we must perform two things: To make our class the delegate of the ad banner view, and secondarily to hide it. Open the <em>ViewController.m</em> file, and go to the <em>viewDidLoad</em> method to add the next couple of lines:</p>
<pre lang="objc">- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Make self the delegate of the ad banner.
    self.adBanner.delegate = self;

    // Initially hide the ad banner.
    self.adBanner.alpha = 0.0;
}
</pre>
<p>As you see, we hide the ad banner view simply by setting its <em>alpha</em> value to 0. Later on, when a delegate method will inform us that an ad is ready to be shown, we&#x2019;ll set that value to 1 again, and to make it more attractive we&#x2019;ll do so using an animation. Changing the alpha value though is not the only way to hide or show the ad banner. There are many other ways to do that, as for example to change the value of the <em>hidden</em> banner&#x2019;s property, or initially place the ad banner view out of the visible screen area. What method you&#x2019;ll finally choose is totally up to you, and to what best suits to your application. For simplicity reasons, I just chose to use the alpha value.</p>
<p>The <em>ADBannerViewDelegate</em> protocol provides five delegate methods in total. Using them, we can manage the ads and ultimately the behavior of our app. Let&#x2019;s see them one by one, and let&#x2019;s discuss shortly what each one is about. Note that in the body of every delegate method I&#x2019;ve intentionally added a <em>NSLog</em> command, so when we run the app later to know which method exactly has been called.</p>
<p>The first method is this:</p>
<pre lang="objc">-(void)bannerViewWillLoadAd:(ADBannerView *)banner{
    NSLog(@&quot;Ad Banner will load ad.&quot;);
}
</pre>
<p>It&#x2019;s easy from the method&#x2019;s name to conclude that this one is called when a new advertisement is about to be loaded. Note that when this method is called the ad is not yet ready to be displayed.</p>
<p>The second delegate method:</p>
<pre lang="objc">-(void)bannerViewDidLoadAd:(ADBannerView *)banner{
    NSLog(@&quot;Ad Banner did load ad.&quot;);
}
</pre>
<p>This one is called after a new ad has been loaded and is ready to be displayed. Later, in this method we&#x2019;ll add the code needed to make the ad banner view visible again, as we&#x2019;ll know that there is an ad to show.</p>
<p>The third delegate method:</p>
<pre lang="objc">-(BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave{
    NSLog(@&quot;Ad Banner action is about to begin.&quot;);

    return YES;
}
</pre>
<p>This method is called when the user taps on the banner, and the ad is going to be displayed in a full size modal view. When that happens, any visual or critical tasks that regard user should be paused until that modal view gets dismissed. The interesting with this method is the value it returns. When the returned value is YES, then the ad will be shown in a full-screen view indeed. However, if the returned value is NO, then nothing will happen when users tap on the ad.</p>
<p>The fourth delegate method:</p>
<pre lang="objc">-(void)bannerViewActionDidFinish:(ADBannerView *)banner{
    NSLog(@&quot;Ad Banner action did finish&quot;);
}
</pre>
<p>This method is called when the full-screen view with the add gets dismissed. It&#x2019;s very useful, as in here any paused or stopped tasks should be put in action again.</p>
<p>Finally, the fifth delegate method:</p>
<pre lang="objc">-(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error{
    NSLog(@&quot;Unable to show ads. Error: %@&quot;, [error localizedDescription]);
}
</pre>
<p>This method is also very useful and important, as it&#x2019;s called when no ads are available to be delivered to the app. When it&#x2019;s called, it&#x2019;s our duty to hide the ad banner view so no blank space is shown to the user when no ads exist.</p>
<p>As you understand, all these delegate methods make the ad handling a really easy task. Now, as we said before, we must show the ad banner view when an advertisement is ready to be displayed, so modify the <em>bannerViewDidLoadAd:</em> delegate method as shown right next:</p>
<pre lang="objc">-(void)bannerViewDidLoadAd:(ADBannerView *)banner{
    NSLog(@&quot;Ad Banner did load ad.&quot;);

    // Show the ad banner.
    [UIView animateWithDuration:0.5 animations:^{
        self.adBanner.alpha = 1.0;
    }];
}
</pre>
<p>You see that using an animation we set the <em>alpha</em> value of the ad banner view to 1 again. That animation will result in a fade-in effect.</p>
<p>Lastly, when there are no ads to be displayed we should hide the ad banner view. Go to the <em>bannerView:didFailToReceiveAdWithError:</em> and add the same code as above. This time make the <em>alpha</em> value 0:</p>
<pre lang="objc">-(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error{
    NSLog(@&quot;Unable to show ads. Error: %@&quot;, [error localizedDescription]);

    // Hide the ad banner.
    [UIView animateWithDuration:0.5 animations:^{
        self.adBanner.alpha = 0.0;
    }];
}
</pre>
<p>The most important work with the ads have been done. In the next section of the tutorial we&#x2019;ll see how to use the other delegate methods, but our app is already pretty functional. So, if you want give it a try and wait for the first ad to be shown.</p>
<h2>Adding the Counter</h2>
<p>The ad banner now works great, and the most important goal, showing and hiding the banner properly, has been achieved. However, this tutorial wouldn&#x2019;t be complete without having discussed about all the important delegate methods, so in this section we are going to make an interesting addition to the project. We are going to use a timer (a <em>NSTimer</em> object) that will count the seconds the user is seeing the View Controller scene, and using the delegate methods provided by iAd framework we&#x2019;ll pause counting when an ad is displayed in full-screen mode. After the ad view has been dismissed, the counter will work again.</p>
<p>Let&#x2019;s get started by declaring three properties that we&#x2019;ll need for our purpose. The first property is the timer object, the second an integer value that will be used to count the seconds elapsed, and finally the third property is a boolean flag that will indicate whether the counting should be paused or not. In the <em>ViewController.m</em> file, go to the private class section, and add the next properties as shown below:</p>
<pre lang="objc">@interface ViewController ()

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic) int secondsElapsed;

@property (nonatomic) BOOL pauseTimeCounting;


@end
</pre>
<p>Now, in the <em>viewDidLoad</em> method let&#x2019;s do some initializations:</p>
<pre lang="objc">- (void)viewDidLoad
{
    [super viewDidLoad];
      ...
     ...

    // Start the timer.
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showTimerMessage) userInfo:nil repeats:YES];

    // Set the initial value for the elapsed seconds.
    self.secondsElapsed = 0;
}
</pre>
<p>As you see in the timer object creation, in the selector parameter is given the <em>showTimerMessage</em> method name. This is a private method that does not exist yet, and it will be called by the timer every one second (the interval argument set to 1.0). Of course, we want our timer to work repeatedly, so we set the <em>repeats</em> parameter value to YES.</p>
<p>Xcode is showing a warning now, because it&#x2019;s unable to find a declaration for the above method. Let&#x2019;s go to fix it by declaring the method first, and then we&#x2019;ll define it. Go back to the private class section, and add the next line:</p>
<pre lang="objc">@interface ViewController ()

...
...

-(void)showTimerMessage;

@end
</pre>
<p>In its definition now, you&#x2019;ll see in the following code fragment that the code execution flow depends on the <em>pauseTimeCounting</em> flag. If its value is false, then we&#x2019;ll keep counting and updating the text of the <em>lblTimerMessage</em>. Apparently, when its value is true we won&#x2019;t count. Notice that before any text update it&#x2019;s necessary to increase the <em>secondsElapsed</em> property&#x2019;s value by one. The implementation is really simple, so there you go:</p>
<pre lang="objc">-(void)showTimerMessage{
    if (!self.pauseTimeCounting) {
        self.secondsElapsed++;

        self.lblTimerMessage.text = [NSString stringWithFormat:@&quot;You&apos;ve been viewing this view for %d seconds&quot;, self.secondsElapsed];
    }
    else{
        self.lblTimerMessage.text = @&quot;Paused to show ad...&quot;;
    }
}
</pre>
<p>Let&#x2019;s get to the point now, and let&#x2019;s see how to use two more iAd delegate methods. The first one we&#x2019;ll see, is the <em>bannerViewActionShouldBegin:willLeaveApplication:</em> one. As I have already said, this method is called after a user has tapped on an ad, and a full-screen view is about to be shown containing the ad. Of course, it&#x2019;s necessary the returned value of that method to be set to YES, otherwise no ad will be displayed. What we want when this method is called is quite simple: To tell our app that the time counting should be paused. To do that, we&#x2019;ll simply change the value of the <em>pauseTimeCounting</em> flag. Let&#x2019;s see the method:</p>
<pre lang="objc">-(BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave{
    NSLog(@&quot;Ad Banner action is about to begin.&quot;);

    self.pauseTimeCounting = YES;

    return YES;
}
</pre>
<p>Apart from pausing the counting process, we must also allow it to continue when a full-image view with an ad has been closed. For that purpose, we&#x2019;ll use the <em>bannerViewActionDidFinish:</em> delegate method. In it, we&#x2019;ll simply change once again the flag&#x2019;s value. Here it is:</p>
<pre lang="objc">-(void)bannerViewActionDidFinish:(ADBannerView *)banner{
    NSLog(@&quot;Ad Banner action did finish&quot;);

    self.pauseTimeCounting = NO;
}
</pre>
<p>That was our last touch! Now, when the ad banner gets tapped the counting will be paused, and it will keep going again once the ad has been dismissed.</p>
<h2>Compile and Run the App</h2>
<p>At this point, feel free to compile and run the app. You will notice that at the bottom of the screen the ad banner will appear after a while, and the counter&#x2019;s value is displayed in the message label. Tap on the ad banner and watch the advertisements in full-screen mode. When you go back to the View Controller scene, you see that the time counting wasn&#x2019;t active while you were viewing ads. If suddenly no ads are being served, don&#x2019;t worry, that&#x2019;s normal. Ad delivery may stop from time to time.</p>
<p>As an extra exercise, if you want try to display the ad banner at the top of the view.</p>
<p><img loading="lazy" decoding="async" width="600" height="265" src="http://www.appcoda.com/wp-content/uploads/2014/06/t14_9_final_big.jpg" alt="Using iAd to Display Banner Ad in Your App" class="aligncenter size-full wp-image-3739"></p>
<p><img loading="lazy" decoding="async" width="600" height="91" src="http://www.appcoda.com/wp-content/uploads/2014/06/t14_10_debugger.jpg" alt="Using iAd to Display Banner Ad in Your App" class="aligncenter size-full wp-image-3740"></p>
<h2>Summary</h2>
<p>Integrating advertisements into an application is a quite common tactic, and a good way to make some earnings while you give you app for free. To tell the truth, maybe you won&#x2019;t make a fortune from ads, but if your app acquire big download numbers then you&#x2019;ll probably have a remarkable revenue. As you saw in this tutorial, there are simple rules regarding the ad banners, and the required code is just a matter of a few lines. So, if you&#x2019;re still thinking about whether you should add ads on your app and how to do it, this is your chance. Of course, you are recommended and encouraged to go through the official documentation as well. I hope this tutorial becomes helpful to all of you, and as always feel free to share any thoughts or comments with us.</p>
<p>For your reference, you can <a href="https://dl.dropboxusercontent.com/u/2857188/iAdDemo.zip?ref=appcoda.com">download the complete Xcode project from here</a>.</p>

<!--kg-card-end: html-->
]]></content:encoded></item><item><title><![CDATA[Integrating Facebook Login in iOS App - The Manual Way]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>In my <a href="http://www.appcoda.com/ios-programming-facebook-login-sdk/">previous tutorial</a>, I presented an easy and fast way to implement the login with Facebook feature. Based on the <em>FBLoginView</em> class, I demonstrated how logging in and out from Facebook can be done in really a few minutes with the assistance of a predefined login button. In this</p>]]></description><link>https://www.appcoda.com/ios-programming-facebook-login-manual/</link><guid isPermaLink="false">66612a0f166d3c03cf011374</guid><category><![CDATA[iOS Programming]]></category><category><![CDATA[Objective C]]></category><dc:creator><![CDATA[Gabriel Theodoropoulos]]></dc:creator><pubDate>Fri, 30 May 2014 00:42:43 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2014/05/facebook-login.jpg" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://www.appcoda.com/content/images/wordpress/2014/05/facebook-login.jpg" alt="Integrating Facebook Login in iOS App - The Manual Way"><p>In my <a href="http://www.appcoda.com/ios-programming-facebook-login-sdk/">previous tutorial</a>, I presented an easy and fast way to implement the login with Facebook feature. Based on the <em>FBLoginView</em> class, I demonstrated how logging in and out from Facebook can be done in really a few minutes with the assistance of a predefined login button. In this tutorial we&#x2019;ll do the exact same thing, but this time we won&#x2019;t use any automatic solution. Instead, we will implement every part of the login process manually and we&#x2019;ll see in some detail level how everything works when connecting to Facebook. That&#x2019;s a useful knowledge to have, as there are many cases that the default login view we saw in the last tutorial isn&#x2019;t handful at all.</p>
<p>Before we start programming, it is necessary to present some basic terms, so you&#x2019;ve got an idea about the whole process. The first important thing you should know, is that after a successful login with Facebook the app receives an <em>access token</em>. This is a unique key, that allows to perform requests and exchange data with Facebook in a secure fashion, without having to authorize the app all the time. One could say that the whole login hassle happens just to get that access token. Once received, and depending on the <em>permissions</em> your app asks for, you can freely get and send data.</p>
<p><img loading="lazy" decoding="async" width="800" height="600" src="http://www.appcoda.com/wp-content/uploads/2014/05/facebook-login.jpg" alt="Integrating Facebook Login in iOS App - The Manual Way" class="aligncenter size-full wp-image-3539" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/facebook-login.jpg 800w, https://www.appcoda.com/content/images/wordpress/2014/05/facebook-login-400x300.jpg 400w" sizes="(max-width: 800px) 100vw, 800px"></p>
<p>The key class of the Facebook SDK that handles everything that has to do with the access token, is the <em>FBSession</em> class. This one, manages all the various <em>session states</em> that a connection can have, and is the one that determines the logged in status. It would be useful to take a quick look at the state <em>lifecycle</em>, as that would help to understand what we&#x2019;ll do next. Let&#x2019;s see some details:</p>
<ul>
<li>When an app is launched, the initial session state, meaning the initial state value set to the <em>FBSession</em> class by default, is the <em>FBSessionStateCreated</em>. The class searches for an existing, stored access token, and if founds one, it goes to the <em>FBSessionStateCreatedTokenLoaded</em>, and then to the <em>FBSessionStateOpen</em>, where the session is open and data exchange can take place with no problem.</li>
<li>When no access token exists and a login process is on the way, then from the initial <em>FBSessionStateCreated</em> state, when the login UI is appeared the state changes to <em>FBSessionStateCreatedOpening</em>. If all goes well on login/app authorization, then the state gets the <em>FBSessionStateOpen</em> value. However, if during the credentials entry or on app authorization the user taps on the Cancel button and stops the login process, then the state gets the <em>FBSessionStateClosedLoginFailed</em> value.</li>
<li>There are cases where the initial permissions asked during login are not enough, so additional permissions are needed to be granted. If that successfully takes place, then the state changes its value from <em>FBSessionStateOpen</em> to <em>FBSessionStateOpenTokenExtended</em>. Note that no extra permissions can be asked if the current session state doesn&#x2019;t have the <em>FBSessionStateOpen</em> value.</li>
<li>Finally, when logging out, then from any of the two open states, the <em>FBSessionStateOpen</em> and the <em>FBSessionStateOpenTokenExtended</em>, the session ends up with the <em>FBSessionStateClosed</em> state value.</li>
</ul>
<p>In the above description, I mentioned a couple of times the term &#x201C;permissions&#x201D;, so now let me make a comment on them. Permissions actually determine what assets, features or resources an app can have access to, and they are separated in two categories: The <em>read</em> and <em>publish</em> permissions. To the read category belong all those that describe access to user info, while to the second one belong all those that allow an app to publish on behalf of the user. If no permissions are requested for a specific resource, then accessing it is impossible. A login process is initiated using read permissions, and always the public user info, or in other words the &#x201C;public_profile&#x201D; permission, is granted by default. When users login with Facebook through an app may become hesitant when they&#x2019;re asked to grant permissions, so make sure to ask only for those permissions that are necessary for the app. We&#x2019;ll talk about permission more later in the tutorial as well.</p>
<p>Finally, a word about the <em>Graph API</em>, as this is a term you&#x2019;ll meet in the sections that follow. The Graph API, is actually the Facebook API for communicating and exchanging data. Is HTTP-based, and it&#x2019;s used for all the tasks you want to do with Facebook. Regarding the Facebook SDK for iOS, there is a wide number of methods that work with it. In this tutorial we&#x2019;ll use just a couple of them. If you are curious though and you&#x2019;d like to see more about it, then feel free to read more on Facebook documentation. Of course, if you&#x2019;re about to develop an app that works with Facebook and does more than logging users in, you definitely need to read some stuff.</p>
<p>All the discussion made so far, will help you understand all that coming next. If you need more theory or to get fundamental knowledge, then there&#x2019;s no better option than visiting the source itself, meaning the Facebook documentation. For now, we&#x2019;ve said enough already, so let&#x2019;s begin doing some work.</p>
<h2>App Overview</h2>
<p>The next figure illustrates the final outcome of our implementation in this tutorial:</p>
<p><img loading="lazy" decoding="async" width="515" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t13_1_final_sample.jpg" alt="Integrating Facebook Login in iOS App - The Manual Way" class="aligncenter size-full wp-image-3526" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t13_1_final_sample.jpg 515w, https://www.appcoda.com/content/images/wordpress/2014/05/t13_1_final_sample-343x300.jpg 343w" sizes="(max-width: 515px) 100vw, 515px"></p>
<p>The main goal is to manage to login with Facebook, and then logout, using a custom button. Further than doing that, we&#x2019;ll also get some piece of the user&#x2019;s public info, the e-mail address and the profile picture after a successful login.</p>
<p>The UI will contain a few controls: Some labels for showing the user&#x2019;s info and the current connection status, an image view for displaying the profile picture, an activity indicator that will animate when opening a session, and of course, the custom login/logout button. We&#x2019;ll see more details about all these subviews when we&#x2019;ll setup the interface.</p>
<p>Lastly, there&#x2019;s a dedicated section in this tutorial almost for every part of the sample app that&#x2019;s about to be implemented. Even though we&#x2019;ll pay some attention to create the app, we&#x2019;ll mostly focus on the login implementation, and all the related stuff.</p>
<p>Note that if you download the sample project, make sure to correctly enter your app&#x2019;s FacebookAppID, FacebookDisplayName string values and the URL Types array. Also, you must necessarily add the Facebook SDK framework to the project. For more information about all that, see the <em>Initial Steps</em> section of the tutorial.</p>
<p>Having said all that, let&#x2019;s get started.</p>
<h2>Creating the App</h2>
<p>As always, the first step we have to do is to create a new sample project. Therefore, launch Xcode and do so. In the initial guide that appears, select the <strong>Single View Application</strong> as the project template, in the <strong>Applications</strong> category, under the <strong>iOS</strong> section.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/05/t13_2_template1.jpg" alt="Integrating Facebook Login in iOS App - The Manual Way" class="aligncenter size-full wp-image-3527" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t13_2_template1.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/05/t13_2_template1-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Click Next to proceed. In the second step of the guide, in the <strong>Product Name</strong> field set the <strong>ManualFBLogin</strong> as the project&#x2019;s name. Also, make sure that in the <strong>Devices</strong> drop down menu, the <strong>iPhone</strong> option is selected.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/05/t13_3_template2.jpg" alt="Integrating Facebook Login in iOS App - The Manual Way" class="aligncenter size-full wp-image-3528" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t13_3_template2.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/05/t13_3_template2-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Click Next, and in the third and last step of the guide select a directory to save the project and then click on the Create button.</p>
<h2>Initial Steps</h2>
<p>This part is very crucial, as it involves the necessary setup needed to be done in both Facebook developers website and Xcode project before writing even a single line of code. In the previous tutorial regarding the Facebook login, I presented in details all the actions you should take, so go in the <a href="http://www.appcoda.com/ios-programming-facebook-login-sdk/">Preparing the Environment</a> section and follow everything described there step by step. Here&#x2019;s a summary of what you should do:</p>
<ol>
<li>Create a new app record on the <a href="https://developers.facebook.com/?ref=appcoda.com">Facebook developers website</a>.</li>
<li>Fill in all the necessary fields, and correctly copy the app&#x2019;s bundle ID.</li>
<li>Add the Facebook SDK framework to the project.</li>
<li>In the .plist file of the project add all the needed keys and the respective values properly.</li>
</ol>
<p>When you are ready with all the above, you can return here and continue with this tutorial. <strong>Don&#x2019;t skip this step.</strong></p>
<h2>Interface Setup</h2>
<p>Our goal here is to configure the interface by adding all the necessary subviews to the <em>View Controller</em> scene, and by declaring and connecting all the respective IBOutlet properties. We will work in the Interface Builder, so click on the <em>Main.storyboard</em> file to let it appear.</p>
<p>The following screenshot demonstrates what the final outcome of our work here will be.</p>
<p><img loading="lazy" decoding="async" width="276" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t13_4_ib_sample.jpg" alt="Integrating Facebook Login in iOS App - The Manual Way" class="aligncenter size-full wp-image-3529" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t13_4_ib_sample.jpg 276w, https://www.appcoda.com/content/images/wordpress/2014/05/t13_4_ib_sample-184x300.jpg 184w" sizes="(max-width: 276px) 100vw, 276px"></p>
<p>The subviews we must add to the interface are the next ones:</p>
<ul>
<li>An <em>image view</em> to display the user&#x2019;s profile picture.</li>
<li>A <em>label</em> to show the user&#x2019;s full name (first and last name).</li>
<li>A <em>label</em> to show the user&#x2019;s e-mail address.</li>
<li>A <em>label</em> centered in the view that will display the status.</li>
<li>An <em>activity indicator view</em> that will animate when the app is opening an existing session.</li>
<li>A <em>button</em> at the bottom of the view, that will be used to log in and out.</li>
</ul>
<p>As you notice, the login button is fully customized and it has nothing to do with the <em>login view</em>, the pre-made login button of the Facebook SDK.</p>
<p>Let&#x2019;s start adding all the subviews one by one and setting all the appropriate attributes of them. For each subview described below, find the appropriate object in the <strong>Object Library</strong> and drag and drop it in the default view.</p>
<h3>UIImageView</h3>
<ul>
<li><strong>Frame</strong>: X=20, Y=60, Width=63, Height=63</li>
</ul>
<h3>UILabel</h3>
<ul>
<li><strong>Frame</strong>: X=91, Y=60, Width=209, Height=63</li>
<li><strong>Text</strong>: <em>None</em> or <em>Fullname</em></li>
<li><strong>Text Color</strong>: White</li>
<li><strong>Font</strong>: System Bold, 15.0</li>
<li><strong>Text Alignment</strong>: Center</li>
<li><strong>Lines</strong>: 5</li>
<li><strong>Line Break</strong>: Word Wrap</li>
</ul>
<h3>UILabel</h3>
<ul>
<li><strong>Frame</strong>: X=20, Y=148, Width=280, Height=21</li>
<li><strong>Text</strong>: <em>None</em> or <em>E-mail</em></li>
<li><strong>Text Color</strong>: White</li>
<li><strong>Font</strong>: System Bold, 15.0</li>
<li><strong>Text Alignment</strong>: Center</li>
</ul>
<h3>UILabel</h3>
<ul>
<li><strong>Frame</strong>: X=20, Y=273, Width=280, Height=21</li>
<li><strong>Text</strong>: <em>You are not logged in.</em></li>
<li><strong>Text Color</strong>: White</li>
<li><strong>Font</strong>: System Bold, 17.0</li>
<li><strong>Text Alignment</strong>: Center</li>
</ul>
<h3>UIActivityIndicator</h3>
<ul>
<li><strong>Frame</strong>: X=150, Y=302, Width=20, Height=20</li>
<li><strong>Style</strong>: White</li>
</ul>
<h3>UIButton</h3>
<ul>
<li><strong>Frame</strong>: X=0, Y=508, Width=320, Height=60</li>
<li><strong>Title</strong>: <em>Login</em></li>
<li><strong>Text Color</strong>: White</li>
<li><strong>Font</strong>: System Bold, 15.0</li>
<li><strong>Background Color</strong>: R=255, G=128, B=0</li>
</ul>
<p>Finally, set the view&#x2019;s background color to R=59, G=89, B=152.</p>
<p>Your scene should now look like the screenshot illustrated at the beginning of this part.</p>
<p>Now that all the necessary subviews have been added to the view, it&#x2019;s time to declare some IBOutlet properties and then connect them to these subviews. Open the <em>ViewController.h</em> file and add the next lines:</p>
<pre lang="objc">@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIButton *btnToggleLoginState;

@property (weak, nonatomic) IBOutlet UIImageView *imgProfilePicture;

@property (weak, nonatomic) IBOutlet UILabel *lblFullname;

@property (weak, nonatomic) IBOutlet UILabel *lblEmail;

@property (weak, nonatomic) IBOutlet UILabel *lblStatus;

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;


@end
</pre>
<p>The name of each property clearly declares its purpose. Further than the above, let&#x2019;s also declare an IBAction method that we&#x2019;ll use to login and logout. Add the next line right after the last property declaration:</p>
<pre lang="objc">- (IBAction)toggleLoginState:(id)sender;
</pre>
<p>Finally, head back to the <em>Main.storyboard</em> file, and connect the IBOutlet properties to the appropriate subviews. Here are the matches:</p>
<ul>
<li>The <em>btnToggleLoginState</em> property must be connected to the login button at the bottom.</li>
<li>The <em>imgProfilePicture</em> property must be connected to the image view.</li>
<li>The <em>lblFullname</em> property must be connected to the label next to the image view.</li>
<li>The <em>lblEmail</em> property must be connected to the e-mail label, right under the image view.</li>
<li>The <em>lblStatus</em> property must be connected to the status label to the center of the view.</li>
<li>The <em>activityIndicator</em> property must be connected to the activity indicator view.</li>
</ul>
<p>Here is a figure illustrating a property connection:</p>
<p><img loading="lazy" decoding="async" width="600" height="419" src="http://www.appcoda.com/wp-content/uploads/2014/05/t13_5_iboutlet_connect.jpg" alt="Integrating Facebook Login in iOS App - The Manual Way" class="aligncenter size-full wp-image-3530" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t13_5_iboutlet_connect.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/05/t13_5_iboutlet_connect-429x300.jpg 429w" sizes="(max-width: 600px) 100vw, 600px"></p>
<h2>Additional In-Code Configuration</h2>
<p>Having finished with the interface configuration, it&#x2019;s time to move on to code. Before we dive into the heart of the topic though, we will perform some code-level setup that will determine the initial state of the app. Note that what we&#x2019;ll do here is not required for the Facebook SDK to work. However it will help you make your project similar to the sample in case you develop following this tutorial step by step. So, here&#x2019;s in short the most important tasks we&#x2019;ll do:</p>
<ul>
<li>We will create a private method to set the hidden state of the subviews.</li>
<li>We will add the necessary code needed to make the image view rounded.</li>
<li>We will change the status bar style, making it have a light color.</li>
</ul>
<p>Let&#x2019;s begin with the easy one. Open the <em>ViewController.m</em> file, and in the <em>viewDidLoad</em> method add the next line:</p>
<pre lang="objc">[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
</pre>
<p>This will turn the dark status bar into a light one.</p>
<p>Next let&#x2019;s make the image view rounded, with a white border around it. In order to do that, we must access the <em>CALayer</em> <em>layer</em> property of it, and set three specific properties of the <em>layer</em> object. However the <em>CALayer</em> class is not part of the <em>UIKit</em> framework, therefore we must import the <em>QuartzCore</em> framework. In the top of the file add the next line:</p>
<pre lang="objc">#import <quartzcore quartzcore.h>
</quartzcore></pre>
<p>The following four lines make the image view rounded, with a white border and 1px thick. Make sure to add them in the <code>viewDidLoad</code> method.</p>
<pre lang="objc">self.imgProfilePicture.layer.masksToBounds = YES;
self.imgProfilePicture.layer.cornerRadius = 30.0;
self.imgProfilePicture.layer.borderColor = [UIColor whiteColor].CGColor;
self.imgProfilePicture.layer.borderWidth = 1.0;
</pre>
<p>Now, let&#x2019;s create a private method that will enable us to hide and show all the user info related subviews, depending on whether the user is logged in or not. At first, we must declare it in the private class section:</p>
<pre lang="objc">@interface ViewController ()

-(void)hideUserInfo:(BOOL)shouldHide;

@end
</pre>
<p>The <em>shouldHide</em> parameter flag will specify if the <em>hidden</em> property of the following subviews will be YES or NO. The method definition:</p>
<pre lang="objc">-(void)hideUserInfo:(BOOL)shouldHide{
    self.imgProfilePicture.hidden = shouldHide;
    self.lblFullname.hidden = shouldHide;
    self.lblTotalFriends.hidden = shouldHide;
}
</pre>
<p>Initially, we want all of the above subviews to be hidden. Later, when the connected state will be determined using the Facebook SDK, they&#x2019;ll become visible if needed. So, let&#x2019;s go to the <code>viewDidLoad</code> method and make a call to this method:</p>
<pre lang="objc">[self hideUserInfo:YES];
</pre>
<p>Besides than making those subviews hidden, it&#x2019;s necessary to hide the activity indicator as well. We wouldn&#x2019;t like the spinner appear with no reason. So, right below the above method call, add the next line:</p>
<pre lang="objc">self.activityIndicator.hidden = YES;
</pre>
<p>Note that the activity indicator will be handled separately from the rest of the subviews. The same applies to the status label.</p>
<p>Finally, let&#x2019;s declare and instantiate an <code>AppDelegate</code> property, which we are going to use later during the implementation. Firstly, import the <code>AppDelegate.h</code> header file:</p>
<pre lang="objc">#import &quot;AppDelegate.h&quot;
</pre>
<p>Next, go to the private class section and add a property declaration as follows:</p>
<pre lang="objc">@property (nonatomic, strong) AppDelegate *appDelegate;
</pre>
<p>Lastly, in the <code>viewDidLoad</code> method, instantiate it:</p>
<pre lang="objc">self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
</pre>
<p>Now we are ready to focus on the login implementation.</p>
<h2>Logging In</h2>
<p>The Facebook SDK contains a great number of libraries and classes. Among them, there is one class that is responsible for handling sessions, therefore its job is to handle the login process as well. That class is named <code>FBSession</code>, and it&#x2019;s the one we need in order to achieve our goal.</p>
<p>The <code>FBSession</code> class implements the next method: </p>
<pre lang="objc">openActiveSessionWithReadPermissions:allowLoginUI:completionHandler:
</pre>
<p>With this one the login process is started. Let&#x2019;s take a quick look at its parameters:</p>
<ul>
<li><em>openActiveSessionWithReadPermissions</em>: The <em>read</em> permissions that are required by the app are provided here. For your knowledge, it&#x2019;s not necessary to request for all permissions at once, as the more they are, the less possible is for the user to authorize and use the app. Additional permissions can be asked during the app execution. There are publish permissions too that can be requested along the way, but we don&#x2019;t care about any of them right now. In this example, we will ask for the <em>public_profile</em> and the <em>email</em> permissions. You can find a full reference about permissions <a href="https://developers.facebook.com/docs/facebook-login/permissions/v2.0?ref=appcoda.com">here</a>.</li>
<li><em>allowLoginUI</em>: This parameter accepts a YES or NO value. If YES, then it shows either the Facebook app (if installed) or Safari to enter credentials if needed, and then to authorize the app.</li>
<li><em>completionHandler</em>: The completion handler block is called when the login process has finished. It returns three parameters: A <em>session (FBSession)</em> object, the session <em>state</em> value, and an <em>error</em> object in case it occurs any. We&#x2019;ll talk more about the session and its various states in the next section of the tutorial.</li>
</ul>
<p>Let&#x2019;s start working now, and we&#x2019;ll discuss every detail along the way. The &#x201C;entry&#x201D; point that we&#x2019;ll begin from, is the <em>toggleLoginState:</em> IBAction method we had previously declared. Using this method, we&#x2019;ll initiate both the login and the logout operations. The first thing we have to consider, is to check whether there is an open session or not. In case there isn&#x2019;t any, then we&#x2019;ll use the method described above to login. However, prior to implementation, make sure to import the Facebook framework at the top of the <em>ViewController.m</em> file:</p>
<pre lang="objc">#import <facebooksdk facebooksdk.h>
</facebooksdk></pre>
<p>Then, let&#x2019;s see the initial implementation of the IBAction method:</p>
<pre lang="objc">- (IBAction)toggleLoginState:(id)sender {
    if ([FBSession activeSession].state != FBSessionStateOpen &amp;&amp;
        [FBSession activeSession].state != FBSessionStateOpenTokenExtended) {

    }
    else{

    }

}
</pre>
<p>A couple of observations here:</p>
<ul>
<li>The current session, also named <em>active session</em>, is accessed just like this: <em>[FBSession activeSession]</em>.</li>
<li>Using the <em>state</em> property of the active session, we determine if there is an open session or not. The two open session states are shown above.</li>
</ul>
<p>Now, instead of directly calling the <em>openActiveSessionWithReadPermissions:allowLoginUI:completionHandler:</em> method of the <em>FBSession</em> class, we&#x2019;ll make a small detour. We&#x2019;ll <em>implement a public method in the AppDelegate class, and in there we&#x2019;ll make the call</em>. That might seem strange to you at the moment, but I have two specific reasons to do that:</p>
<ol>
<li>Later on, we&#x2019;ll have to use the <em>openActiveSessionWithReadPermissions:allowLoginUI:completionHandler:</em> method again to open a stored session, and it wouldn&#x2019;t be a good idea to write the same code twice.</li>
<li>It is a more general solution that can be used in larger projects.</li>
</ol>
<p>Having said that, open the <em>AppDelegate.h</em> file, and firstly import the Facebook framework:</p>
<pre lang="objc">#import <facebooksdk facebooksdk.h>
</facebooksdk></pre>
<p>Then add the next method declaration:</p>
<pre lang="objc">@interface AppDelegate : UIResponder <uiapplicationdelegate>

@property (strong, nonatomic) UIWindow *window;


-(void)openActiveSessionWithPermissions:(NSArray *)permissions allowLoginUI:(BOOL)allowLoginUI;

@end
</uiapplicationdelegate></pre>
<p>The parameters we&#x2019;ll provide to the <em>openActiveSessionWithPermissions:allowLoginUI:</em> custom method will be passed to the <em>openActiveSessionWithReadPermissions:allowLoginUI:completionHandler:</em> of the <em>FBSession</em> class. What follows next is the method&#x2019;s definition, but what are we going to do there?</p>
<p>Well, the answer lies to the completion handler of the <em>openActiveSessionWithReadPermissions:allowLoginUI:completionHandler:</em> method, where we must handle the various session states. In our case, after the user has logged in, we must update the UI and show the user&#x2019;s info. The same should happen later on, when we&#x2019;ll open an existing session on a subsequent app launch. However, we can&#x2019;t access the <em>ViewController</em>&#x2018;s interface through the <em>AppDelegate</em> class directly. The simplest solution would be to inform the <em>ViewController</em> when the login/session opening process is over, and perform in that class all the session handling. A simple way to do that is using a <em>notification</em>. Indeed, we&#x2019;ll post a notification when the completion handler will be called, and along with it we&#x2019;ll post the completion handler&#x2019;s results (session, session state, error).</p>
<p>So, speaking with code this time, go to the <em>AppDelegate.m</em> file to define the public method. Here it is:</p>
<pre lang="objc">-(void)openActiveSessionWithPermissions:(NSArray *)permissions allowLoginUI:(BOOL)allowLoginUI{    
    [FBSession openActiveSessionWithReadPermissions:permissions
                                       allowLoginUI:allowLoginUI
                                  completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {

                                      // Create a NSDictionary object and set the parameter values.
                                      NSDictionary *sessionStateInfo = [[NSDictionary alloc] initWithObjectsAndKeys:
                                                                        session, @&quot;session&quot;,
                                                                        [NSNumber numberWithInteger:status], @&quot;state&quot;,
                                                                        error, @&quot;error&quot;,
                                                                        nil];

                                      // Create a new notification, add the sessionStateInfo dictionary to it and post it.
                                      [[NSNotificationCenter defaultCenter] postNotificationName:@&quot;SessionStateChangeNotification&quot;
                                                                                          object:nil
                                                                                        userInfo:sessionStateInfo];

                                  }];
}
</pre>
<p>You see that we initialize a <em>NSDictionary</em> object and we set all the values returned by the completion handler to it. Then, a new <em>NSNotification</em> object is posted, using the custom name <em>SessionStateChangeNotification</em> and the dictionary created right before.</p>
<p>Now, back at the <em>toggleLoginState:</em> IBAction method in the <em>ViewController.m</em> file, let&#x2019;s make a call to the above method:</p>
<pre lang="objc">- (IBAction)toggleLoginState:(id)sender {
    if ([FBSession activeSession].state != FBSessionStateOpen &amp;&amp;
        [FBSession activeSession].state != FBSessionStateOpenTokenExtended) {

        [self.appDelegate openActiveSessionWithPermissions:@[@&quot;public_profile&quot;, @&quot;email&quot;] allowLoginUI:YES];
    }
    else{

    }

}
</pre>
<p>To recap, when the user taps on the Login custom button, the <em>openActiveSessionWithPermissions:allowLoginUI:</em> public method of the <em>AppDelegate</em> is first called, which invokes in turn the <em>openActiveSessionWithReadPermissions:allowLoginUI:completionHandler:</em> of the <em>FBSession</em> class. Once the whole login process is over, we inform the <em>ViewController</em> using a notification, where we&#x2019;ll handle the various session states in a while.</p>
<p>Before we reach the end of this section is necessary to perform a couple more steps: The first is to implement an application delegate method, the next one:</p>
<pre lang="objc">-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{    
    return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
}
</pre>
<p>This one is called after the login credentials entry and app authorization have finished in Facebook app or Safari. The <code>[FBAppCall handleOpenURL:url sourceApplication:sourceApplication]</code> manages the results of all the actions taken outside the app (successful login/authorization or cancelation), and properly directs the login flow back in our app again.</p>
<p>The second step is to take our measures in case the user leaves the app while the login dialog is visible either in Facebook app or in Safari. In such a case, it&#x2019;s necessary to use the Facebook framework for doing some cleanup and removing any unfinished session processes. Thankfully this is easy and it takes only a single line. Go to the <code>applicationDidBecomeActive:</code> of the application delegate, and add the next one:</p>
<pre lang="objc">- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [FBAppCall handleDidBecomeActive];
}
</pre>
<p>The <em>handleDidBecomeActive</em> method of the <em>FBAppCall</em> class will check for an unfinished login process at the next app launch, and it will clear all the unnecessary &#x201C;leftovers&#x201D;, if any found.</p>
<h2>Handling Session States</h2>
<p>Posting the notification after a finished login process is an important step, but it consists only of the half work that must be done. The other half regards two things: To observe for the notification and to handle the session states.</p>
<p>Let&#x2019;s begin by observing for the notification. Open the <em>ViewController.m</em> file, and head to the <em>viewDidLoad</em> method. In there, add the following code snippet:</p>
<pre lang="objc">[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleFBSessionStateChangeWithNotification:) name:@&quot;SessionStateChangeNotification&quot; object:nil];
</pre>
<p>With that statement, we force our class to observe for the notification specified by the given name, and when it arrives we will call the <em>handleFBSessionStateChangeWithNotification:</em> method. This is a private method that we are about to implement right now.</p>
<p>Initially, go to the private class section and declare it:</p>
<pre lang="objc">@interface ViewController ()

-(void)handleFBSessionStateChangeWithNotification:(NSNotification *)notification;

@end
</pre>
<p>In its definition we&#x2019;ll handle the session states we are interested in. These are:</p>
<ul>
<li><em>FBSessionStateOpen</em>: When a session is open.</li>
<li><em>FBSessionStateClosed</em>: When a session is closed.</li>
<li><em>FBSessionStateClosedLoginFailed</em>: When the user cancels the login /authorization process.</li>
</ul>
<p>Actually, here is what we are going to do:</p>
<ol>
<li>From the notification parameter object, we&#x2019;ll extract the dictionary.</li>
<li>We&#x2019;ll assign to local variables the session state value and the error object which we&#x2019;ll take from the dictionary.</li>
<li>We&#x2019;ll show the appropriate status message, along with the activity indicator.</li>
<li>If no error occurred, then if the session is open we&#x2019;ll make a call to Facebook Graph API to get all the info we want. If the session is closed or failed, we&#x2019;ll update the UI.</li>
<li>If an error occurred, we&#x2019;ll output the error description and perform any UI-related tasks.</li>
</ol>
<p>The next code fragment contains all these:</p>
<pre lang="objc">-(void)handleFBSessionStateChangeWithNotification:(NSNotification *)notification{
    // Get the session, state and error values from the notification&apos;s userInfo dictionary.
    NSDictionary *userInfo = [notification userInfo];

    FBSessionState sessionState = [[userInfo objectForKey:@&quot;state&quot;] integerValue];
    NSError *error = [userInfo objectForKey:@&quot;error&quot;];

    self.lblStatus.text = @&quot;Logging you in...&quot;
    [self.activityIndicator startAnimating];
    self.activityIndicator.hidden = NO;

    // Handle the session state.
    // Usually, the only interesting states are the opened session, the closed session and the failed login.
    if (!error) {
        // In case that there&apos;s not any error, then check if the session opened or closed.
        if (sessionState == FBSessionStateOpen) {
            // The session is open. Get the user information and update the UI.

            [self.btnToggleLoginState setTitle:@&quot;Logout&quot; forState:UIControlStateNormal];

        }
        else if (sessionState == FBSessionStateClosed || sessionState == FBSessionStateClosedLoginFailed){
            // A session was closed or the login was failed or canceled. Update the UI accordingly.            
            [self.btnToggleLoginState setTitle:@&quot;Login&quot; forState:UIControlStateNormal];            
            self.lblStatus.text = @&quot;You are not logged in.&quot;
            self.activityIndicator.hidden = YES;
        }
    }
    else{
        // In case an error has occured, then just log the error and update the UI accordingly.
        NSLog(@&quot;Error: %@&quot;, [error localizedDescription]);

        [self hideUserInfo:YES];        
        [self.btnToggleLoginState setTitle:@&quot;Login&quot; forState:UIControlStateNormal];

    }
}
</pre>
<p>If you look closely at the code, you&#x2019;ll notice that we&#x2019;ve handled everything we care about, but we didn&#x2019;t get the user&#x2019;s info yet. That&#x2019;s something we&#x2019;ll do right next, as I&#x2019;d like us to focus our attention a bit more on that.</p>
<h2>Getting User Info</h2>
<p>Summarizing what we&#x2019;ve done so far, I&#x2019;d say that the most important steps we have managed to complete are the login process initiation and the session state handling. What we haven&#x2019;t still done, is to get the user&#x2019;s information after a successful login or after having loaded an existing, and display it on-screen.</p>
<p>Getting user&#x2019;s data is easy. It takes only a call to the <em>startWithGraphPath:parameters:HTTPMethod:completionHandler:</em> method of the <em>FBRequestConnection</em> class. As you conclude from the method&#x2019;s name, it makes a HTTP request to the appropriate API and sends all the provided parameters, which are given as a dictionary object. This method is a general one and can be used for several kinds of requests.</p>
<p>Back to our sample app now, let me specify the kind of info we&#x2019;ll ask for the connected user. We&#x2019;re going to get the first name, the last name, the e-mail address and the profile picture URL, which we&#x2019;ll then use for showing the user&#x2019;s image on the view. The dictionary object, and according to the Facebook Graph API, is expressed as follows:</p>
<pre lang="objc">@{@&quot;fields&quot;: @&quot;first_name, last_name, picture.type(normal), email&quot;}
</pre>
<p>Notice that for the profile picture we use the <em>picture.type(normal)</em> value, asking from Facebook to return the normal size picture. There are four picture types that can be used:</p>
<ol>
<li>Small</li>
<li>Normal</li>
<li>Large</li>
<li>Square</li>
</ol>
<p>The completion handler of the <em>startWithGraphPath:parameters:HTTPMethod:completionHandler:</em> method contains three parameters:</p>
<ol>
<li>A <em>FBRequestConnection</em> object. We won&#x2019;t need it here.</li>
<li>An <em>id</em> object that contains the actual data. In our case, this is going to be a <em>NSDictionary</em> object.</li>
<li>An error pointer.</li>
</ol>
<p>If no error occurred during the request, then we&#x2019;ll get the user data from the returned dictionary and we&#x2019;ll assign it as a value to the appropriate subview. Also, we&#x2019;ll get the picture from the returned URL, and after all UI controls have taken their values, we&#x2019;ll just unhide them. In case of an error, we&#x2019;ll only output its description.</p>
<p>In the next code fragment it&#x2019;s given the <em>handleFBSessionStateChangeWithNotification:</em> method implementation once again. However, this time contains the call to the <em>startWithGraphPath:parameters:HTTPMethod:completionHandler:</em> method in the case of an open session.</p>
<pre lang="objc">-(void)handleFBSessionStateChangeWithNotification:(NSNotification *)notification{
    // Get the session, state and error values from the notification&apos;s userInfo dictionary.
    NSDictionary *userInfo = [notification userInfo];

    FBSessionState sessionState = [[userInfo objectForKey:@&quot;state&quot;] integerValue];
    NSError *error = [userInfo objectForKey:@&quot;error&quot;];

    self.lblStatus.text = @&quot;Logging you in...&quot;
    [self.activityIndicator startAnimating];
    self.activityIndicator.hidden = NO;

    // Handle the session state.
    // Usually, the only interesting states are the opened session, the closed session and the failed login.
    if (!error) {
        // In case that there&apos;s not any error, then check if the session opened or closed.
        if (sessionState == FBSessionStateOpen) {
            // The session is open. Get the user information and update the UI.            
            [FBRequestConnection startWithGraphPath:@&quot;me&quot;
                                         parameters:@{@&quot;fields&quot;: @&quot;first_name, last_name, picture.type(normal), email&quot;}
                                         HTTPMethod:@&quot;GET&quot;
                                  completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                                      if (!error) {
                                          // Set the use full name.
                                          self.lblFullname.text = [NSString stringWithFormat:@&quot;%@ %@&quot;,
                                                                   [result objectForKey:@&quot;first_name&quot;],
                                                                   [result objectForKey:@&quot;last_name&quot;]
                                                                   ];

                                          // Set the e-mail address.
                                          self.lblEmail.text = [result objectForKey:@&quot;email&quot;];

                                          // Get the user&apos;s profile picture.
                                          NSURL *pictureURL = [NSURL URLWithString:[[[result objectForKey:@&quot;picture&quot;] objectForKey:@&quot;data&quot;] objectForKey:@&quot;url&quot;]];
                                          self.imgProfilePicture.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:pictureURL]];

                                          // Make the user info visible.
                                          [self hideUserInfo:NO];

                                          // Stop the activity indicator from animating and hide the status label.
                                          self.lblStatus.hidden = YES;
                                          [self.activityIndicator stopAnimating];
                                          self.activityIndicator.hidden = YES;
                                      }
                                      else{
                                          NSLog(@&quot;%@&quot;, [error localizedDescription]);
                                      }
                                  }];

            [self.btnToggleLoginState setTitle:@&quot;Logout&quot; forState:UIControlStateNormal];
        }
        else if (sessionState == FBSessionStateClosed || sessionState == FBSessionStateClosedLoginFailed){
            // A session was closed or the login was failed. Update the UI accordingly.
            [self.btnToggleLoginState setTitle:@&quot;Login&quot; forState:UIControlStateNormal];
            self.lblStatus.text = @&quot;You are not logged in.&quot;
            self.activityIndicator.hidden = YES;
        }
    }
    else{
        // In case an error has occurred, then just log the error and update the UI accordingly.
        NSLog(@&quot;Error: %@&quot;, [error localizedDescription]);        
        [self hideUserInfo:YES];        
        [self.btnToggleLoginState setTitle:@&quot;Login&quot; forState:UIControlStateNormal];

    }
}
</pre>
<p>If you add a <em>NSLog</em> command to the above completion handler and print the <em>result</em> object, then you&#x2019;ll get something like the next one:</p>
<pre lang="objc">2014-05-25 11:39:14.573 ManualFBLogin[748:90b] {
    email = &quot;gabriel_dqhaczs_tester@tfbnw.net&quot;
    &quot;first_name&quot; = Gabriel;
    id = 1377148289239707;
    &quot;last_name&quot; = Tester;
    picture =     {
        data =         {
            &quot;is_silhouette&quot; = 0;
            url = &quot;https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/t1.0-1/s100x100/10390960_1392345714386631_6289945774589507432_s.jpg&quot;
        };
    };
}
</pre>
<p>As you see, the <em>picture</em> object is a dictionary which in turn contains the <em>data</em> dictionary, and that&#x2019;s the one containing the picture data we want. Based on that, it&#x2019;s easy to understand how the NSURL object in the above method is formed:</p>
<pre lang="objc">NSURL *pictureURL = [NSURL URLWithString:[[[result objectForKey:@&quot;picture&quot;] objectForKey:@&quot;data&quot;] objectForKey:@&quot;url&quot;]];
</pre>
<p>Before we consider our work in this section done, I must say that using the <em>startWithGraphPath:parameters:HTTPMethod:completionHandler:</em> method is not the only way to get the user&#x2019;s public info. Actually, there&#x2019;s a method dedicated to that, the <em>startForMeWithCompletionHandler:</em>, and it&#x2019;s part of the <em>FBRequestConnection</em> class. It has a disadvantage though, as it doesn&#x2019;t return the URL of the profile picture and that&#x2019;s why we didn&#x2019;t use it in the first place.</p>
<p>If you wish so, feel free to make a call to that method and print to the debugger the results it brings back. Make sure to add it in the open session case, right before or after the <em>startWithGraphPath:parameters:HTTPMethod:completionHandler:</em> call. Here&#x2019;s how you should invoke it:</p>
<pre lang="objc">[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {

                if (!error) {
                    NSLog(@&quot;%@&quot;, result);
                }

            }];
</pre>
<p>This will output to the debugger something similar to this:</p>
<pre lang="objc">{
    email = &quot;gabriel_dqhaczs_tester@tfbnw.net&quot;
    &quot;first_name&quot; = Gabriel;
    gender = male;
    id = 1377148289239707;
    &quot;last_name&quot; = Tester;
    link = &quot;https://www.facebook.com/app_scoped_user_id/1377148289239707/&quot;
    locale = &quot;en_US&quot;
    name = &quot;Gabriel Tester&quot;
    timezone = 3;
    &quot;updated_time&quot; = &quot;2014-05-21T18:49:16+0000&quot;
    verified = 0;
}
</pre>
<p>Using this method just like that provides a nice way to find out what the public info regarding the user is, and what the names of the relevant fields are.</p>
<p>Now it&#x2019;s a good time to run the app for first time. Initially, tap on the login button to get connected:</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t13_6_logged_out.jpg" alt="Integrating Facebook Login in iOS App - The Manual Way" class="aligncenter size-full wp-image-3531" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t13_6_logged_out.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/05/t13_6_logged_out-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<p>Provide your credentials and authorize the app:</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t13_7_authorize.jpg" alt="Integrating Facebook Login in iOS App - The Manual Way" class="aligncenter size-full wp-image-3532" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t13_7_authorize.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/05/t13_7_authorize-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<p>If everything runs normally, then you&#x2019;ll see your info appearing in the app, once you get back to it.</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t13_8_logged_in.jpg" alt="Integrating Facebook Login in iOS App - The Manual Way" class="aligncenter size-full wp-image-3533" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t13_8_logged_in.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/05/t13_8_logged_in-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<h2>Opening a Session</h2>
<p>If you try to run the app twice, you&#x2019;ll notice that even though you&#x2019;ve logged in the first time, you seem to be logged out upon the second launch. Actually, you are logged in indeed, but for the time being the app doesn&#x2019;t know that. Fixing that situation is easy, but before we do so, let&#x2019;s see some more details.</p>
<p>Every time that you successfully login with Facebook, the Facebook API returns some info regarding the connection, and saves it persistently. The most important piece of information contained is the access token that defines the session state and allows you to make requests without additional authorization to be needed upon subsequent app launches. Along with that token, its expiration date and some other stuff are included as well. The truth is that you don&#x2019;t need to be aware of all these, as the Facebook SDK handles it behind the scenes. However,it is always good to know where everything is stored, so you can manually check if the proper info has been returned when debugging.</p>
<p>All the session-related info is stored into a .plist file, which you can find in a path similar to this (make sure that you have the hidden files visible):</p>
<pre lang="objc">/Users/gabriel/Library/Application Support/iPhone Simulator/7.1/Applications/A62A3F77-6A8C-477D-96FE-C32FB23B166B/Library/Preferences
</pre>
<p>The file of our app is named <em>com.Your_Company_Name.ManualFBLogin.plist</em>, and if you open it you can see if the token info is really there. Note that you shouldn&#x2019;t edit it, otherwise expect something bad to happen in the app.</p>
<p><img loading="lazy" decoding="async" width="600" height="115" src="http://www.appcoda.com/wp-content/uploads/2014/05/t13_9_plist.jpg" alt="Integrating Facebook Login in iOS App - The Manual Way" class="aligncenter size-full wp-image-3534"></p>
<p>Having said all the above, let&#x2019;s focus on our app again. As I said, for the time being the app doesn&#x2019;t know if you are logged in or not, therefore will present you the default, logged out state on a subsequent launch. The goal is to make it read the above file in order to determine the connected state and then open the existing session. This should be done when the app is launched, and a good place to do so would be the <em>application:didFinishLaunchingWithOptions:</em> method of the application delegate. However, keep in mind that when the session state changes, we want to update our UI, and the problem that arises here is that this method is called before the view controller is loaded. That means that even if we load and open the session, the view controller won&#x2019;t be ready soon enough to observe for the notification that will be posted upon a session state change, so the UI won&#x2019;t be refreshed.</p>
<p>The solution in our case to load and open the session in the <em>applicationDidBecomeActive:</em> method of the <em>AppDelegate</em> class. If you remember, in a previous section of this tutorial we had added the next line in that method:</p>
<pre lang="objc">[FBAppCall handleDidBecomeActive];
</pre>
<p>Now, we must modify once again that method. In the next code segment is presented the code that must be added in order to properly open a saved session:</p>
<pre lang="objc">- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    if ([FBSession activeSession].state == FBSessionStateCreatedTokenLoaded) {
        [self openActiveSessionWithPermissions:nil allowLoginUI:NO];
    }

    [FBAppCall handleDidBecomeActive];
}
</pre>
<p>Initially, the Facebook SDK checks if there&#x2019;s a stored access token. If so, then we call the <em>openActiveSessionWithPermissions:allowLoginUI:</em> public method we had created previously, providing no permissions and not allowing the login UI to appear. That way, the app loads from the .plist file the saved session, and then posts the notification. The notification is received by the <em>ViewController</em> class, and ultimately the session is properly handled. If a valid access token exists, and if the session normally opens, then our app requests the user&#x2019;s info from Facebook every time the app launches.</p>
<p>If you add the above few lines and you run the app again, you&#x2019;ll see that this time you won&#x2019;t seem to be logged out.</p>
<p>Before closing, there are three things I&#x2019;d like to mention:</p>
<ol>
<li>The option to open the session in the <em>applicationDidBecomeActive:</em> is not a rule. I just chose to do so in this project, so the session opening works flawlessly with the custom notification posting and the session state handling. In your projects you could either choose this way, or open the session anywhere that best serves you.</li>
<li>This is a sample project, so every time the app launches we request the user&#x2019;s info from Facebook. In a real-world app though, and depending on the security level of your app, you could store the user&#x2019;s info locally, and make requests to update it only when that&#x2019;s necessary.</li>
<li>In the beginning of this section I showed you where the access token along with the rest of the session info is saved to an app. However, Facebook allows to use a custom strategy for storing the session and managing all the procedures that deal with it (such as opening or loading it). That&#x2019;s something out of the scope of this tutorial, so I won&#x2019;t get into any details at all. I believe that you should be aware of that, so if you&#x2019;d like to learn more you just have to visit the official Facebook documentation.</li>
</ol>
<h2>Logging Out</h2>
<p>Everything is ready, apart from one thing. We still haven&#x2019;t implemented the logout functionality, and that&#x2019;s necessary for having a complete login mechanism.</p>
<p>Logging out is literally a matter of a single line of code. If you recall, in the <em>toggleLoginState:</em> IBAction method we have two cases: The first one where no open session exists and the user should login, and the opposite case (the <em>else</em> case), where the user is already logged in and now should log out.</p>
<p>In the next code fragment you are given the whole IBAction method, including the logout functionality. As you&#x2019;ll see, we also update the UI accordingly.</p>
<pre lang="objc">- (IBAction)toggleLoginState:(id)sender {
    if ([FBSession activeSession].state != FBSessionStateOpen &amp;&amp;
        [FBSession activeSession].state != FBSessionStateOpenTokenExtended) {

        [self.appDelegate openActiveSessionWithPermissions:@[@&quot;public_profile&quot;, @&quot;email&quot;] allowLoginUI:YES];

    }
    else{
        // Close an existing session.
        [[FBSession activeSession] closeAndClearTokenInformation];

        // Update the UI.
        [self hideUserInfo:YES];
        self.lblStatus.hidden = NO;
        self.lblStatus.text = @&quot;You are not logged in.&quot;
    }

}
</pre>
<h2>Compile and Run the App</h2>
<p>Reaching almost at the end of the tutorial, it&#x2019;s hard to imagine that you haven&#x2019;t still compiled and run the app. However, if you haven&#x2019;t done so, then this is the right time to do it. Before you click on the Run button on Xcode, make sure that you have properly configured both Facebook account and Xcode, and you followed everything step by step described in the previous sections.</p>
<p>The next animated graphics illustrate the whole process of login/logout we implemented in this tutorial:</p>
<p><img loading="lazy" decoding="async" width="313" height="587" src="http://www.appcoda.com/wp-content/uploads/2014/05/t13_10_login_process.gif" alt="Integrating Facebook Login in iOS App - The Manual Way" class="aligncenter size-full wp-image-3535"></p>
<h2>Summary</h2>
<p>This tutorial, in combination with the previous one regarding the Facebook login view, gives you all the tools you need for logging in with Facebook. As you see, it&#x2019;s not difficult to do so as long as you follow some specific rules. I should mention that no special reference to error handling was made. That was in purpose, as it would be out of my goals to discuss it here. There&#x2019;s an extensive description about that topic in Facebook documentation, so I&#x2019;d advise you to give it a reading. Lastly, as a final word I would suggest to always stay up-to-date regarding the changes in Facebook SDK, as there might be significant modifications from version to version. I hope you&#x2019;ve been helped by this post, and as always, leave us your thoughts.</p>
<p>For your reference, you can download the complete Xcode project from <a href="https://dl.dropboxusercontent.com/u/2857188/ManualFBLogin.zip?ref=appcoda.com">here</a>.</p>

<!--kg-card-end: html-->
]]></content:encoded></item><item><title><![CDATA[How to Integrate Facebook Login in iOS App]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>Integrating Facebook features into an app is nowadays a quite common task, and one of the most important steps in the integration process is the login functionality implementation. Logging in with Facebook not only allows you to attach a social characteristic into your app, but it can also be used</p>]]></description><link>https://www.appcoda.com/ios-programming-facebook-login-sdk/</link><guid isPermaLink="false">66612a0f166d3c03cf011373</guid><category><![CDATA[iOS Programming]]></category><category><![CDATA[Objective C]]></category><dc:creator><![CDATA[Gabriel Theodoropoulos]]></dc:creator><pubDate>Mon, 19 May 2014 23:48:14 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1517292987719-0369a794ec0f?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fGZhY2Vib29rfGVufDB8fHx8MTcxNjM1NjE2N3ww&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://images.unsplash.com/photo-1517292987719-0369a794ec0f?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fGZhY2Vib29rfGVufDB8fHx8MTcxNjM1NjE2N3ww&amp;ixlib=rb-4.0.3&amp;q=80&amp;w=2000" alt="How to Integrate Facebook Login in iOS App"><p>Integrating Facebook features into an app is nowadays a quite common task, and one of the most important steps in the integration process is the login functionality implementation. Logging in with Facebook not only allows you to attach a social characteristic into your app, but it can also be used as a login system instead of creating a custom one. By adding it you offer to users a familiar way to authenticate, considering that the majority of users use Facebook.</p>
<p>Facebook integration is natively supported since iOS 6, even though it&#x2019;s still necessary to manually add the Facebook SDK into your projects. There are two ways provided by the SDK for logging in with Facebook. The first one consists of a relatively easy solution, as it uses a predefined login view which manages all the session and login related stuff. The second one is a more &#x201C;heavy&#x201D; approach as everything must be implemented and handled by the developer, but on the other hand the login process can be highly customized. The method that should be used into a project definitely depends on the app&#x2019;s requirements. If the predefined, familiar <em>Login with Facebook</em> button fits to the application&#x2019;s look and feel, then this should be the number #1 option. If further customization is needed, then the programmatic option is a one-way road.</p>
<p><img loading="lazy" decoding="async" width="800" height="666" src="http://www.appcoda.com/wp-content/uploads/2014/05/facebook-login-feature.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3513" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/facebook-login-feature.jpg 800w, https://www.appcoda.com/content/images/wordpress/2014/05/facebook-login-feature-360x300.jpg 360w" sizes="(max-width: 800px) 100vw, 800px"></p>
<p>In this tutorial we are going to see how to login with Facebook using the first way, so let&#x2019;s talk a bit more about it. The login view, or programmatically speaking the <em>FBLoginView</em> class, provides a standard Facebook button to log in and log out from the app. The appearing position of the view can be specified, but neither its size or its title can be changed. Actually, the title is automatically set according to the logged in status at a given time. Behind the scenes, the class is responsible to carry out all the heavy work. It manages all the communication with Facebook, it handles the various session changes, it persistently stores the authentication token received from Facebook after a successful login, it checks for an existing token upon the application launch, and a lot more. Developers don&#x2019;t have to deal with all that details, or even care about them. They are only required to add the login view to the appropriate view controller, define all the desired <em>permissions</em> and implement a few delegate methods to handle the login state changes.<br>
<!--more--></p>
<p>The login with Facebook relies on the <strong>Single Sign-On (SSO)</strong> access control system, according to which users can access multiple applications having logged in just once and using the same session. If, for example, you have the Facebook app installed on your device and you have already logged in, then when you&#x2019;ll use for first time another application that implements the login with Facebook feature you&#x2019;ll see that you&#x2019;re already connected and no credentials are required again. You&#x2019;ll only need to authorize the app. The basic idea behind this, is the fact that a device (such as the iPhone) is personal, so users are not obliged to provide the login info repeatedly. There is a drawback though; when you log out from an app you actually just de-authorize its access to your account. You are not really disconnected from Facebook, so even if you expect so, no credentials will be asked the next time you&#x2019;ll use the app. In that case, you have to explicitly logout using the Facebook app or through the iPhone/iPad settings.</p>
<p>By finishing this tutorial you&#x2019;ll be able to login with Facebook and to use the method you will learn in your projects too. However, I would strongly advise you to read the <a href="https://developers.facebook.com/docs/facebook-login/ios/v2.0?ref=appcoda.com">official Facebook documentation</a> regarding the login workflow and the Single Sign-On technology. Doing so will also help you to obtain a deep understanding on the current topic.</p>
<h2>App Overview</h2>
<p>Looking at the big picture of this tutorial, one could say that is separated in two major parts. The first one is dedicated to the preparation needed to be done both in Facebook and Xcode prior to any implementation. In this, we will see how to create an application record on Facebook, how to setup Xcode and add the Facebook SDK framework, and how to use information taken from the newly created Facebook record to the project. Once this necessary step is over, we will be devoted to the implementation. By implementing a sample project, we will see how the login view and the <em>FBLoginClass</em> work by logging in and out. Finally, we will implement all those needed delegate methods that will inform our app about the connection state, and we display specific user information on-screen.</p>
<p>The next figure gives you an idea of the final goal of this tutorial.</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_26_loginview_complete.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3506" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t12_26_loginview_complete.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/05/t12_26_loginview_complete-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<p>Notice that if you download the sample project, you must perform some preparatory steps before you run it. Specifically, you must firstly set your own Facebook app&#x2019;s info in the project&#x2019;s .plist file. Be sure to correctly enter your app&#x2019;s <em>FacebookAppID, FacebookDisplayName</em> string values and the <em>URL Types</em> array. If you skip it, you won&#x2019;t be able to try out the sample project. Also, you must necessarily to add the Facebook SDK framework to the project. To accomplish all these, follow the guidelines described in the <em>Preparing the Environment</em> section.</p>
<h2>Project Creation</h2>
<p>Let&#x2019;s start working by launching Xcode and creating a new project for the sample application, as it&#x2019;s shown in the next figure:</p>
<p><img loading="lazy" decoding="async" width="600" height="352" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_1_xcode_welcome.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3481" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t12_1_xcode_welcome.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/05/t12_1_xcode_welcome-511x300.jpg 511w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>In the guide that appears, select the <strong>Single View Application</strong> in the <strong>Application</strong> category, under the <strong>iOS</strong> section. Click on the Next button to proceed. In the second step, enter the <strong>LoginSampleFB</strong> value in the <strong>Product Name</strong> field, and make sure that in the <strong>Devices</strong> drop down menu the <em>iPhone</em> option is selected.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_3_template2.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3483" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t12_3_template2.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/05/t12_3_template2-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Click on the Next button once again, and in the last step select a directory to save the project. Once you do so, click on the Create button and you are ready.</p>
<h2>Preparing the Environment</h2>
<p>Before using any Facebook SDK feature, it&#x2019;s necessary to perform some prerequisite tasks. These include preparation on both the Facebook platform and the Xcode project, as well as adding the Facebook SDK framework on the app. Of course, you must have a Facebook account active. In case you don&#x2019;t, then create one and then return here to continue.</p>
<p>For starters, open Safari or any other browser you use, and go to the <a href="http://developers.facebook.com/?ref=appcoda.com">Facebook Developers website</a>. Click on the <strong>Log In</strong> link at the far right side of the screen, and in the next page enter your credentials.</p>
<p><img loading="lazy" decoding="async" width="500" height="177" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_5_facebook_login.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3485"></p>
<p>After you have logged in, you will be probably guided to your Facebook home page. In this case, at the top bar, click on the most-right link with a down arrow image, and from the menu that will appear select the <strong>Manage Apps</strong> option.</p>
<p><img loading="lazy" decoding="async" width="205" height="357" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_6_manage_apps_option.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3486" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t12_6_manage_apps_option.jpg 205w, https://www.appcoda.com/content/images/wordpress/2014/05/t12_6_manage_apps_option-172x300.jpg 172w" sizes="(max-width: 205px) 100vw, 205px"></p>
<p>Next, from the top menu again, click on the <strong>Apps</strong> and then on the <strong>Create a New App</strong> option. As I have already said, for the purpose of this tutorial we are going to create a sample application which you can delete later.</p>
<p><img loading="lazy" decoding="async" width="235" height="77" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_7_create_newapp_option.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3487"></p>
<p>In the window that pops up, in the <strong>Display Name</strong> field enter the <strong>LoginSample</strong> value as the app&#x2019;s name. Also, in the <strong>Category</strong> drop down menu select any category you want, just don&#x2019;t leave it with its default value. As you see in the next figure, I set the <strong>Education</strong> value.</p>
<p><img loading="lazy" decoding="async" width="600" height="328" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_8_create_newapp.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3488" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t12_8_create_newapp.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/05/t12_8_create_newapp-548x300.jpg 548w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Click on the <strong>Create App</strong> button, and then enter the captcha code you see on your screen in the security check window. Once you&#x2019;ve finished, the new app will be created and you&#x2019;ll be guided to the app&#x2019;s dashboard.</p>
<p>The next step is to enable the app login from iOS. Click on the <strong>Settings</strong> option in the left menu, and in the main area click on the <strong>+Add Platform</strong> big button.</p>
<p><img loading="lazy" decoding="async" width="600" height="267" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_9_add_platform.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3489"></p>
<p>In the new window, select the <strong>iOS</strong> platform. A new panel is appeared on the dashboard titled <em>iOS</em>. In the <strong>Bundle ID</strong> field, it&#x2019;s very important to enter the <em>exact same to the project&#x2019;s Bundle Identifier</em> value, otherwise the app users won&#x2019;t be able to be authorized. So, go back to Xcode, click on the project target on the <strong>Project Navigator</strong> pane, and under the <strong>General</strong> tab copy the value of the <strong>Bundle Identifier</strong> field.</p>
<p><img loading="lazy" decoding="async" width="528" height="207" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_10_xcode_bundleid.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3490"></p>
<p>Return on the Facebook dashboard, and paste or type the Bundle Identifier in the <strong>Bundle ID</strong> field. Also, make sure to <em>enable the <strong>Single Sign On</strong> toggle button</em>. Finally, click on the <strong>Save Changes</strong> button and this step is ready. Don&#x2019;t logout from the dashboard though, as we have not finished yet.</p>
<p><img loading="lazy" decoding="async" width="600" height="208" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_11_ios_platform_config.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3491"></p>
<p>Next, visit <a href="https://developers.facebook.com/docs/ios/?ref=appcoda.com">this link</a>, download the Facebook SDK for iOS and install the package following the instructions shown on-screen. By default, the package is extracted on the Documents directory of your user account on your computer. You can either leave it there, or move it to another directory. In this tutorial, I presume that the SDK resides in the ~/USER/Documents directory. Once you have finished with the package extraction, open the <em>FacebookSDK</em> directory, and then <em>drag and drop the FacebookSDK.framework on Xcode, under the Frameworks group</em>. In the modal window that Xcode presents, unselect the <strong>Copy items into destination group&#x2019;s folder (if needed)</strong> checkbox, so the framework won&#x2019;t be actually copied on the project, just a reference to it to be created. By doing so, when you download and extract a new version of the SDK your project will be automatically updated when you re-open it. Leave the rest of options as they are, and click on the Finish button.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_12_framework_add.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3492" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t12_12_framework_add.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/05/t12_12_framework_add-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>There is one final step needed to be performed, and that is to add three new keys to the project&#x2019;s .plist file. So, open it by clicking on the <strong>Supporting Files</strong> group in the Project Navigator and then on the <strong>FBLoginSample-Info.plist</strong> file. Add a new key named <strong>FacebookAppID</strong>, and as its value paste the <strong>App ID</strong> value which you can copy from the Facebook dashboard, at the top of it. Similarly, add the <strong>FacebookDisplayName</strong> key, and in its value paste the <strong>Display Name</strong> which you can also copy from the dashboard.</p>
<p><img loading="lazy" decoding="async" width="600" height="182" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_13_appid_displayname_dashboard.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3493"></p>
<p>Finally, create a new key named <strong>URL Types</strong>, and set its type to <em>array</em> with one item only. Give it the <strong>URL Schemes</strong> title and make it an array too. In the one and only item that should be contained, set the app ID value you copied from the Facebook dashboard, prefixing it with the <em>fb</em> literal. The next figure illustrates all the three additions on the .plist file:</p>
<p><img loading="lazy" decoding="async" width="590" height="154" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_14_plist.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3494"></p>
<p>All steps described here are mandatory for every app that is supposed to integrate Facebook features.</p>
<h2>Creating Test Users</h2>
<p>During the development stage of an app, and especially when authentication is involved in it, it&#x2019;s generally a bad habit to use your normal account to perform all the required testings. Thankfully, Facebook supports the creation and usage of fake, test users per app. These users can&#x2019;t harm your account, and of course, they can be deleted at any time, usually after the app has been developed. You can create as many of them as you want, you can &#x201C;baptize&#x201D; them as you want or let Facebook compose random names, and you can assign to a test user other test users as friends. You can even login to a test user&#x2019;s account if it was a normal user.</p>
<p>To create a test user (at least) for the sample app that we will implement here, go to the Facebook dashboard of the LoginSample app, and select the <strong>Roles</strong> option at the left menu.</p>
<p><img loading="lazy" decoding="async" width="192" height="121" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_15_roles_menu.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3495"></p>
<p>In the main dashboard area, click at the <strong>Test Users</strong> link at the top of it, and then click on the <strong>Add</strong> button, as you see in this figure:</p>
<p><img loading="lazy" decoding="async" width="600" height="164" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_16_test_users_link.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3496"></p>
<p>A small window is appeared, where you set the number of test users you want to add, as well as some other options. If you want to create just one user, leave everything as they are and simply click on the <strong>Create Test Users</strong> button.</p>
<p><img loading="lazy" decoding="async" width="440" height="445" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_17_create_test_users.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3497" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t12_17_create_test_users.jpg 440w, https://www.appcoda.com/content/images/wordpress/2014/05/t12_17_create_test_users-296x300.jpg 296w" sizes="(max-width: 440px) 100vw, 440px"></p>
<p>You could skip the creation of a new test user in case Facebook adds one by default, named <em>Open Graph Test User</em>. Anyway, here is the list of test users as they are shown on my dashboard, where everything has been automatically created:</p>
<p><img loading="lazy" decoding="async" width="600" height="253" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_18_test_users.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3498"></p>
<p>At the right of the test users there are some options, which you can use to rename them, login to their fake account or add friends. Feel free to use them and see what they are for. </p>
<p>Later on we are going to use the e-mail address of a test user to login with Facebook. As a last word, I would recommend to edit the test user you&#x2019;re about to use and set a password, so you won&#x2019;t encounter any problems during the login process.</p>
<h2>Interface Setup</h2>
<p>All the required preparation has been done, so we are now ready to proceed to implementation. As I have already said in the introduction, we are going to add a pre-made view, existing already built in the Facebook SDK. This view is based on a class named <em>FBLoginView</em>, and it has two advantages:</p>
<ol>
<li>It automatically displays the log in/log out Facebook button depending on the connection state.</li>
<li>It handles all the session related stuff, connection states and basic data fetching under the hood.</li>
</ol>
<p>From the developer&#x2019;s point of view, using the login view consists of a two-step process in general. The first one includes all the necessary tasks needed to be done in order to display the view, and the second involves the implementation of some delegate methods for handling all changes been made on the login and session state.</p>
<p>In the default view of the <em>ViewController</em> class we are going to add various subviews, and the most of the will be used to display the user&#x2019;s information after a successful login. Specifically, the most important subview that we will add is the login view, which actually is the login button. Further than that, we will use three <em>UILabel</em> objects to display:</p>
<ul>
<li>The current login status.</li>
<li>The user&#x2019;s name.</li>
<li>The user&#x2019;s e-mail address.</li>
</ul>
<p>Finally, we will have one more <em>UIView</em> object to show the user&#x2019;s profile image. When the user is logged out, the all labels and the profile picture view will be hidden, with just one exception; the login status label.</p>
<p>Let&#x2019;s get started by opening the <em>Main.storyboard</em> file. Add the following subviews to the <em>View Controller</em> scene:</p>
<ol>
<li><strong>UIView</strong></li>
<ul>
<li><em>Frame</em>: X=60, Y=430, Width=200, Height=50</li>
</ul>
<li><strong>UILabel</strong></li>
<ul>
<li><em>Frame</em>: X=20, Y=32, Width=280, Height=21</li>
<li><em>Text Alignment</em>: Center</li>
</ul>
<li><strong>UIView</strong></li>
<ul>
<li><em>Frame</em>: X=85, Y=61, Width=150, Height=150</li>
</ul>
<li><strong>UILabel</strong></li>
<ul>
<li><em>Frame</em>: X=20, Y=219, Width=280, Height=21</li>
<li><em>Text Alignment</em>: Center</li>
<li><em>Font</em>: System Bold</li>
</ul>
<li><strong>UILabel</strong></li>
<ul>
<li><em>Frame</em>: X=20, Y=248, Width=280, Height=21</li>
<li><em>Text Alignment</em>: Center</li>
<li><em>Font Size</em>: 14.0</li>
</ul>
</ol>
<p><img loading="lazy" decoding="async" width="250" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_19_ib_viewcontroller.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3499" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t12_19_ib_viewcontroller.jpg 250w, https://www.appcoda.com/content/images/wordpress/2014/05/t12_19_ib_viewcontroller-166x300.jpg 166w" sizes="(max-width: 250px) 100vw, 250px"></p>
<p>In order for the two UIView objects to properly work, we must modify their classes and set the Facebook-related ones. Specifically, for the UIView at the bottom of the interface (#1 in the above list), in the <strong>Class* field of the </strong>Custom Class** section in the <strong>Identity Inspector</strong>, we must set the <strong>FBLoginValue</strong>, as shown below:</p>
<p><img loading="lazy" decoding="async" width="600" height="424" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_20_fbloginview_class.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3500" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t12_20_fbloginview_class.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/05/t12_20_fbloginview_class-424x300.jpg 424w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>For the profile image view, meaning the second UIView object (#3 in the list above), we must set the <strong>FBProfilePictureView</strong> as its class name:</p>
<p><img loading="lazy" decoding="async" width="600" height="268" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_21_fbprofilepicture_class.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3501"></p>
<p>Setting these custom classes to the above views is not enough to make them work as expected. One more touch is required, and that is to make a call to both of these classes in the <em>application:didFinishLaunchingWithOptions:</em> method of the <em>AppDelegate</em> class. However, we must import the Facebook SDK libraries to the class firstly, so open the <em>AppDelegate.m</em> file and add the next command at the top of it:</p>
<pre lang="objc">#import <facebooksdk facebooksdk.h>
</facebooksdk></pre>
<p>Now, go to the <em>AppDelegate.m</em> file and in the <em>application:didFinishLaunchingWithOptions:</em> delegate method add the next two lines:</p>
<pre lang="objc">- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    [FBLoginView class];
    [FBProfilePictureView class];

    return YES;
}
</pre>
<p>Now that the first contact with the Facebook SDK has been made, let&#x2019;s create some IBOutlet properties for the subviews we added to the interface, and then we&#x2019;ll make the connections. Open the <em>ViewController.h</em> file, and add the next property declarations:</p>
<pre lang="objc">@interface FirstViewController : UIViewController

property (weak, nonatomic) IBOutlet FBLoginView *loginButton;

@property (weak, nonatomic) IBOutlet UILabel *lblLoginStatus;

@property (weak, nonatomic) IBOutlet UILabel *lblUsername;

@property (weak, nonatomic) IBOutlet UILabel *lblEmail;

@property (weak, nonatomic) IBOutlet FBProfilePictureView *profilePicture;

@end
</pre>
<p>Of course, you should import the Facebook SDK library here as well:</p>
<pre lang="objc">#import <facebooksdk facebooksdk.h>
</facebooksdk></pre>
<p>Note: It&#x2019;s possible for Xcode to issue some errors, even when you import the above file. That&#x2019;s probably caused because Xcode does not correctly &#x201C;see&#x201D; the path to the Facebook framework. There is a workaround for that:</p>
<ol>
<li>Go to the project target and open the <strong>Build Settings</strong> tab.</li>
<li>Scroll down until you find the <strong>Search Paths</strong> section</li>
<li>Click on the <strong>Framework Search Paths</strong> key and press the Return key on your keyboard to edit the value.</li>
<li>You should see something similar to this: <em>$(inherited) /Users/gabriel/Documents/FacebookSDK</em>. Delete the <em>$(inherited)</em> term, and include the remaining string value in double quotes, just like it&#x2019;s shown in the next figure:</li>
</ol>
<p><img loading="lazy" decoding="async" width="600" height="156" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_22_fix_searchpaths.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3502"></p>
<p>Finally, go to the <em>Main.storyboard</em> file and connect all IBOutlet properties to the appropriate subviews. Specifically, be sure to match:</p>
<ol>
<li>The <em>loginButton</em> property to the <em>FBLoginView</em> view at the bottom side of the scene.</li>
<li>The <em>lblLoginStatus</em> property to the first, top-most UILabel.</li>
<li>The <em>lblUsername</em> property to the second UILabel where the logged in user&#x2019;s name will appear.</li>
<li>The <em>profilePicture</em> property to the <em>FBProfilePictureView</em> view.</li>
<li>The <em>lblEmail</em> property to the last UILabel object.</li>
</ol>
<p><img loading="lazy" decoding="async" width="600" height="573" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_23_iboutlet_connection.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3503" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t12_23_iboutlet_connection.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/05/t12_23_iboutlet_connection-314x300.jpg 314w" sizes="(max-width: 600px) 100vw, 600px"></p>
<h2>Logging In and Out</h2>
<p>By simply doing all the previous preparation, the login view is ready to work. When the login button will be tapped, the user credentials must be given in order to get authenticated. This can take place in two ways: Either through the Safari app, or through the Facebook app if it is installed on your device (note that the Facebook app works only on a real device, not in the Simulator). Once the login info has been provided, our app must take the control again, but besides that, the Facebook SDK must handle and determine the login process.</p>
<p>Therefore, before we give a try to the app, we must add the necessary code that will do the above. First of all, open the <em>AppDelegate.m</em> file and add the following delegate method:</p>
<pre lang="objc">-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{

}
</pre>
<p>The iOS will call this method after the user has authorized the app through Safari of the Facebook app. In here we will add just one line to let Facebook SDK handle the login result and modify the login view accordingly. Behind the scenes, the authentication token received by Facebook will be persistently stored, and the session state will get changed.</p>
<p>In the next code fragment, you see the necessary code added in the above method that handles the login process:</p>
<pre lang="objc">-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{

    return [FBAppCall handleOpenURL:url
                  sourceApplication:sourceApplication];
}
</pre>
<p>Additionally, we must take care so all subviews to be hidden until the logged in state is determined, except for the login status label. They should become visible only after a successful login and after their values have been set, otherwise they must remain hidden. We&#x2019;ll create a small private method to accomplish this. Open the <em>ViewController.m</em> file, and in the private class section add the next declaration:</p>
<pre lang="objc">@interface ViewController ()

-(void)toggleHiddenState:(BOOL)shouldHide;

@end
</pre>
<p>Next, define that method:</p>
<pre lang="objc">-(void)toggleHiddenState:(BOOL)shouldHide{
    self.lblUsername.hidden = shouldHide;
    self.lblEmail.hidden = shouldHide;
    self.profilePicture.hidden = shouldHide;
}
</pre>
<p>It&#x2019; obvious that the <em>shouldHide</em> parameter value defines the hidden state of the subviews. Now, let&#x2019;s call it in the <em>viewDidLoad</em> method, so initially the subviews are hidden. Also, along with the call to this method, we will set the empty string as the login status label text value:</p>
<pre lang="objc">- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self toggleHiddenState:YES];
    self.lblLoginStatus.text = @&quot;&quot;;

}
</pre>
<p>It&#x2019;s always necessary to specify the <em>read permissions</em> you want for your app when logging in with Facebook. The Facebook SDK uses by default the <em>public_profile</em> permissions, independently on whether you specify or not any. Using it, the user&#x2019;s public info (such as name, profile picture, friends, etc) is returned. However, even though the SDK uses the <em>public_profile</em> automatically, it is recommended to specifically set it along with any other permissions you want to ask for. In this sample app we want to get the user&#x2019;s e-mail address as well, therefore the <em>email</em> permission is required too.</p>
<p>Right next it&#x2019;s shown the way you can use to specify the permissions you need. Note that you must add it to the <em>viewDidLoad</em> method:</p>
<pre lang="objc">self.loginButton.readPermissions = @[@&quot;public_profile&quot;, @&quot;email&quot;];
</pre>
<p>As a footnote, in case you want permissions other than for the public profile, the user&#x2019;s e-mail address and the friends list, or if you need post permissions, your app must be approved by Facebook before it goes live to the App Store. If it won&#x2019;t be approved, the Facebook-related features won&#x2019;t work when your app is live.</p>
<p>Build and run the app now for first time. Tap (or click) on the <em>Login with Facebook</em> button, and be prepared to enter your credentials. In a previous section of the tutorial we talked about test users, so I would advise you to use such an account in order to make your testings. When you&#x2019;ll go back on the app, you will see that the login view title has changed to <em>Log out</em>. Nothing else happens yet, but that&#x2019;s something we&#x2019;ll fix next.</p>
<p>Note that if you test the app on a real device and you have the Facebook app installed, then in case you have logged in with Facebook through that app, you won&#x2019;t be asked again to enter your credentials, just to authorize the app. That&#x2019;s the meaning of the Single Sign-On after all.</p>
<p><img loading="lazy" decoding="async" width="600" height="262" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_24_login_process.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3504"></p>
<p>If you try to log out, an action sheet asking for confirmation will appear, as shown below:</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_25_logout_confirmation.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3505" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t12_25_logout_confirmation.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/05/t12_25_logout_confirmation-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<h2>Handling States</h2>
<p>If you have successfully logged in and logged out, then you see that the login view makes it really easy to get connected to Facebook. For the time being though, the only thing that gets changed is the button&#x2019;s view, nothing else. In this section, we will add all those required delegate methods that will enable us to know if we are connected or not, and then display or hide the appropriate information.</p>
<p>There are four delegate methods that should be implemented in total. Before we add any of them, we must make our class, the <em>ViewController</em>, to conform to a certain protocol, the <em>FBLoginViewDelegate</em>. Open the <em>ViewController.h</em> file, and in the header line adopt the protocol, just like it&#x2019;s shown below:</p>
<pre lang="objc">@interface ViewController : UIViewController <fbloginviewdelegate>
</fbloginviewdelegate></pre>
<p>Now, open the <em>ViewController.m</em> file, and before the implementation of the delegate methods, let&#x2019;s make our class the delegate of the login view. Simply go to the <em>viewDidLoad:</em> method and add this line:</p>
<pre lang="objc">self.loginButton.delegate = self;
</pre>
<p>Let&#x2019;s focus now on the delegate methods. The first one we&#x2019;ll talk about, it is called when the user is logged in. Using it, we can change the <em>hidden</em> state of our subviews, and set the current login status value. Right next it&#x2019;s shown its implementation:</p>
<pre lang="objc">-(void)loginViewShowingLoggedInUser:(FBLoginView *)loginView{
    self.lblLoginStatus.text = @&quot;You are logged in.&quot;;

    [self toggleHiddenState:NO];
}
</pre>
<p>Two simple tasks are performed here: The appropriate message is set as the text of the status label, and the rest of the subviews are becoming visible.</p>
<p>Now that both the profile picture view and the username label can be shown when we have logged in, they must be assigned with values too. This will take place to another delegate method, which provides us with the info we want. That method contains a <em>FBGraphUser</em> object as parameter, which actually is a NSDictionary object, and it contains all the public info of the logged in user. Here is the implementation:</p>
<pre lang="objc">-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<fbgraphuser>)user{
    NSLog(@&quot;%@&quot;, user);
    self.profilePicture.profileID = user.id;
    self.lblUsername.text = user.name;
    self.lblEmail.text = [user objectForKey:@&quot;email&quot;];
}
</fbgraphuser></pre>
<p>I intentionally added a NSLog command in the above method, just to let you see the data contained in the <em>user</em> object. By assigning the <em>id</em> property as the profile ID in the profile picture view, the Facebook SDK downloads the appropriate picture and displays it. If no user picture has been specified, then the default image of the Facebook user will be used. Lastly, the user&#x2019;s name and the e-mail address values are set to the appropriate labels.</p>
<p>With the above two delegate methods, we managed to handle case where the user has logged in. Now, we must deal with the log out. For this case, there&#x2019;s another delegate method, in which we will simply change the status text on the status label and we will hide the rest of the subviews. Here it is:</p>
<pre lang="objc">-(void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView{
    self.lblLoginStatus.text = @&quot;You are logged out&quot;;

    [self toggleHiddenState:YES];
}
</pre>
<p>There is one delegate method remaining, and that is to handle any errors that may occur. In this sample, we won&#x2019;t do any actual error handling, we&#x2019;ll just display the error on the debugger. However, in a real application you should handle all errors according to your app&#x2019;s requirements.</p>
<pre lang="objc">-(void)loginView:(FBLoginView *)loginView handleError:(NSError *)error{
    NSLog(@&quot;%@&quot;, [error localizedDescription]);
}
</pre>
<p>With the above four methods implemented, you can test the app once again. This time, when you have logged in, you&#x2019;ll see the user&#x2019;s name, the profile picture and the e-mail address displayed on the view.</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t12_26_loginview_complete.jpg" alt="How to Integrate Facebook Login in iOS App" class="aligncenter size-full wp-image-3506" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t12_26_loginview_complete.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/05/t12_26_loginview_complete-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<h2>Summary</h2>
<p>Login with Facebook consists of one of the best solutions when you need to add a SSO-oriented login system to your app. By performing some simple steps as described in this tutorial, you gain multiple advantages: You get rid of the hassle to create your own login and authentication mechanism, and you offer your users a familiar technology to work with. Featuring well-known experiences surely leads to more attractive apps, and more potential users. Social apps cover a big part of the available app spectrum, and knowing how to deal with Facebook login and Facebook technologies in general is almost mandatory. Closing, I hope this tutorial to be beneficial to all, and that you&#x2019;ll add what you&#x2019;ve learned here to your code toolbox.</p>
<p>For your reference, you can <a href="https://dl.dropboxusercontent.com/u/2857188/LoginSampleFB.zip?ref=appcoda.com">download the complete Xcode project from here</a>. As always, leave me comment if you have any question or feedback.</p>

<!--kg-card-end: html-->
]]></content:encoded></item><item><title><![CDATA[Introduction to UIActionSheet and UIPopoverController]]></title><description><![CDATA[<!--kg-card-begin: html-->
<p>All mobile applications, no matter what they are about, they have one common and obvious characteristic: They offer <em>interaction</em>, which means that they are not static, but require input or actions needed to be taken by users from time to time in order to function properly. One quite usual behavior,</p>]]></description><link>https://www.appcoda.com/uiactionsheet-uipopovercontroller-tutorial/</link><guid isPermaLink="false">66612a0f166d3c03cf011372</guid><category><![CDATA[iOS Programming]]></category><category><![CDATA[Objective C]]></category><dc:creator><![CDATA[Gabriel Theodoropoulos]]></dc:creator><pubDate>Fri, 09 May 2014 17:50:00 GMT</pubDate><media:content url="https://www.appcoda.com/content/images/wordpress/2014/05/uiactionsheet-featured.jpg" medium="image"/><content:encoded><![CDATA[
<!--kg-card-begin: html-->
<img src="https://www.appcoda.com/content/images/wordpress/2014/05/uiactionsheet-featured.jpg" alt="Introduction to UIActionSheet and UIPopoverController"><p>All mobile applications, no matter what they are about, they have one common and obvious characteristic: They offer <em>interaction</em>, which means that they are not static, but require input or actions needed to be taken by users from time to time in order to function properly. One quite usual behavior, is the ability to provide ways that allow users to make <em>choices</em> or take decisions where it&#x2019;s needed, and ultimately act that way on the applications&#x2019; data or functionalities. iOS SDK provides a pre-made action-taking view controller, the <strong>UIActionSheet</strong>.</p>
<p>Action sheets consist of a really convenient and fast way to display a bunch of options that the user should select from, and it is widely used in great number of applications. Its disadvantage though is that it adopts the iOS&#x2019;s look and feel without being able to be graphically modified, therefore it might not fit to applications with customized GUI. </p>
<p>Beyond action sheets, another very important and cool tool designed especially for the iPad, is the <strong>UIPopoverController</strong>. A popover controller is actually a <em>container</em> which is used to display content on top of another content. What makes it unique is the fact that it can be displayed almost everywhere around the screen of the iPad, but usually it&#x2019;s shown near to the button that caused its appearing with a nice arrow pointing to the button&#x2019;s direction. iOS by default encloses action sheets in popover controllers on iPad, but they can also be manually created for custom content.</p>
<p><img loading="lazy" decoding="async" width="730" height="642" src="http://www.appcoda.com/wp-content/uploads/2014/05/uiactionsheet-featured.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3469" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/uiactionsheet-featured.jpg 730w, https://www.appcoda.com/content/images/wordpress/2014/05/uiactionsheet-featured-341x300.jpg 341w" sizes="(max-width: 730px) 100vw, 730px"></p>
<p>Before we begin working with those two view controllers, let&#x2019;s do some more talking about them in order to get to know their basics, and then we&#x2019;ll proceed on how to use them in projects. So, let me start by telling that both the UIActionSheet and UIPopoverController exist to serve the same purpose, and that is to provide a quick way for presenting content to the user. This content can be either a button-based menu (action sheet), or anything else originating from a view controller (popover controller). Undoubtably, they are both pretty useful tools, and everyone developing for iOS should master both of them. Their great difference lies to where each one is used, and that&#x2019;s the essential fact you should be aware of: An action sheet can be used on any iOS device (iPhone, iPad), but a popover controller can be used only on iPad, as I have already said.</p>
<p>Focusing now a bit on the UIActionSheet, right next is shown a sample of it on iPhone (that&#x2019;s an action sheet we&#x2019;ll create next in this tutorial):</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_1_normal_action_sheet.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3452" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t11_1_normal_action_sheet.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/05/t11_1_normal_action_sheet-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<p>As you can see in the figure above, an action sheet can have three different kind of buttons: A <em>destructive</em> button displayed in red and usually used to highlight deletion actions, a <em>cancel</em> button that simply makes the action sheet to be dismissed, and a bunch of other normal buttons, whose number can vary depending on the provided options to the user. When an action sheet is presented, all of those buttons can be used, or just a combination of them, but surely the action sheet can&#x2019;t be empty. We&#x2019;ll see examples of that along our way in this tutorial.</p>
<p>When working on iPad, actions sheets are displayed embedded into popover controllers. From the developers&#x2019; point of view, no action is required for that, as the iOS automatically does it. However, it&#x2019;s on the programmer&#x2019;s hands to properly display the popover controller with the action sheet in it, and stay aligned to the Human Interface Guidelines. Further than that, keep in mind that the <em>cancel</em> button of the action sheet is not displayed on iPad, as tapping anywhere else but the action sheet is the same as tapping on the cancel button.</p>
<p>About the UIPopoverController now, the next figure illustrates a popover controller on iPad (again, this is a popover we&#x2019;ll create in this tutorial later on):</p>
<p><img loading="lazy" decoding="async" width="438" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_2_uipopovercontroller_example.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3453" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t11_2_uipopovercontroller_example.jpg 438w, https://www.appcoda.com/content/images/wordpress/2014/05/t11_2_uipopovercontroller_example-292x300.jpg 292w" sizes="(max-width: 438px) 100vw, 438px"></p>
<p>If you have never worked with it, then it might sounds hard to make use of it. However, as you&#x2019;ll ultimately find out, initializing and using popover controllers is just a matter of a couple of lines. Popovers are excellent tools, as they can show content almost anywhere you want around the screen. They are suitable for cases that user must interact in a quick fashion with a view controller, without losing from his eyes the current one. Besides that, the arrow pointing their origin is a beautiful visual effect, always attractive to the users.</p>
<p>If you feel you want to learn more theoretical stuff about action sheets or popover controllers, then visit Apple&#x2019;s documentation and have an in-depth study. That&#x2019;s something I definitely encourage you to do. However, now it is time to proceed and see how everything works in practice.</p>
<h2>App Overview</h2>
<p>Now that you have a taste of what we are going to work with in this tutorial, let&#x2019;s take a glance at the sample application we are about to develop next. So, let me begin by saying that we will deal firstly with action sheets. We&#x2019;ll see how they can be presented, how to customize the displayed options, and of course, how to handle the user response and actions. All that will be done for the iPhone device family initially, through simple and practical examples.</p>
<p>Next, we&#x2019;ll see how action sheets work on iPad devices, and how they are displayed enclosed in popover controllers (UIPopoverController) automatically by the system. Actually, we will see how the examples implemented for the iPhone apply on iPad, and what differences may exist.</p>
<p>Finally, we&#x2019;ll focus on the popover controller itself. We will programmatically initialize and display one, in which we&#x2019;ll add the contents of a new view controller.</p>
<p>Everything will be presented in details, so if you are new to all these, be sure that you&#x2019;ll definitely learn something when you reach the end of the tutorial. Having said all that, let&#x2019;s get started.</p>
<h2>App Creation</h2>
<p>Let&#x2019;s get started by creating the sample app of this tutorial. Launch Xcode and create a new project. In the first step of the guide that appears, select the <strong>Single View Application</strong> as the template of the app, in the <strong>Application</strong> category under the <strong>iOS</strong> section. Then click on the Next button.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_3_template1.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3454" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t11_3_template1.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/05/t11_3_template1-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>In the second step, in the <strong>Product Name</strong> field set the <strong>ActionSheetDemo</strong> value. Then in the <strong>Devices</strong> drop down menu, select the <strong>Universal</strong> option so it works on both the iPhone and the iPad. Once you do so, click on the Next button again.</p>
<p><img loading="lazy" decoding="async" width="600" height="405" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_4_template2.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3455" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t11_4_template2.jpg 600w, https://www.appcoda.com/content/images/wordpress/2014/05/t11_4_template2-444x300.jpg 444w" sizes="(max-width: 600px) 100vw, 600px"></p>
<p>Finally, in the last step select a destination directory to save the project and click Create. It is now ready, so we can keep on going with the UIActionSheet demonstration.</p>
<h2>Presenting a UIActionSheet</h2>
<p>Now that there is a project to work on, let&#x2019;s see how a UIActionSheet view controller can be displayed. Before doing so though, open the <em>Main_iPhone.storyboard</em> file by clicking on its name on the Project Navigator. Once the Interface Builder is appeared, add the following three <em>UIButton</em> objects, as described and shown below:</p>
<p><em>Button #1:</em><br>
1. <strong>Title</strong>: <em>Normal Action Sheet</em><br>
2. <strong>Frame</strong>: X=81, Y=228, Width=159, Height=33</p>
<p><em>Button #2:</em><br>
1. <strong>Title</strong>: <em>Delete Confirmation Action Sheet</em><br>
2. <strong>Frame</strong>: X=32, Y=269, Width=256, Height=33</p>
<p><em>Button #3:</em><br>
1. <strong>Title</strong>: <em>Colors Action Sheet</em><br>
2. <strong>Frame</strong>: X=83, Y=310, Width=154, Height =33</p>
<p><img loading="lazy" decoding="async" width="462" height="297" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_5_iphone_ib_buttons.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3456"></p>
<p>Now, open the <em>ViewController.h</em> file, and declare the next three IBAction methods:</p>
<pre lang="objc">@interface ViewController : UIViewController

- (IBAction)showNormalActionSheet:(id)sender;

- (IBAction)showDeleteConfirmation:(id)sender;

- (IBAction)showColorsActionSheet:(id)sender;

@end
</pre>
<p>Then, return to the Interface Builder and connect each one to the appropriate button, matching the method names with the button titles. Get finished with that and then open the <em>ViewController.m</em> file to write some code.</p>
<p>Let&#x2019;s begin by implementing the <em>showNormalActionSheet:</em> IBAction method, and let&#x2019;s display our first action sheet. What you always have to do is to initialize a UIActionSheet object (either local or a class property) in the way that&#x2019;s shown below:</p>
<pre lang="objc">
&#xA0;- (IBAction)showNormalActionSheet:(id)sender {

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@&quot;What do you want to do with the file?&quot;
                                                             delegate:self
                                                    cancelButtonTitle:@&quot;Cancel&quot;
                                               destructiveButtonTitle:@&quot;Delete it&quot;
                                                    otherButtonTitles:@&quot;Copy&quot;, @&quot;Move&quot;, @&quot;Duplicate&quot;, nil];


}
</pre>
<p>As you may conclude from the above code, in this action sheet we hypothetically provide to the user some file handling options. Let&#x2019;s talk a bit about the initialization method, which as you see it accepts a great number of parameters. The first one is a title that&#x2019;s displayed on top of the action sheet with small letters, and usually is a prompt message or a question about the action that&#x2019;s about to be taken. The second one is the delegate of the action sheet, which can be set to <em>nil</em> if you are not planning to implement any delegate method (something that&#x2019;s really rare though), otherwise the <em>self</em> object is usually set. The <em>cancelButtonTitle</em> parameter accepts a desired title for the cancel button, which always is placed at the bottom of the action sheet, separately from the others, and as its name suggests, it simply forces the action sheet to be dismissed without any action performed. Next, the destructive button is a special button colored in red, and is used to indicate a critical action, such as a deletion. In the respective parameter you set its title. This button is always first in the buttons&#x2019; order. Finally, the <em>otherButtonTitles</em> parameter accepts a nil terminated string, and in here the titles of the rest buttons existing on the action sheet are set. All of the normal buttons are positioned between the destructive and the cancel button.</p>
<p>When initializing an action sheet, it&#x2019;s not mandatory to have all kind of buttons if you don&#x2019;t need them. To avoid a button&#x2019;s appearance on the sheet, you simply set the nil value to the respective parameter and the button won&#x2019;t appear. We&#x2019;ll see that later.</p>
<p>Now, to make the action sheet appear when the button gets tapped, you need to add one more command right after the initialization:</p>
<pre lang="objc">- (IBAction)showNormalActionSheet:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@&quot;What do you want to do with the file?&quot;
                                                             delegate:self
                                                    cancelButtonTitle:@&quot;Cancel&quot;
                                               destructiveButtonTitle:@&quot;Delete it&quot;
                                                    otherButtonTitles:@&quot;Copy&quot;, @&quot;Move&quot;, @&quot;Duplicate&quot;, nil];

    [actionSheet showInView:self.view];
}
</pre>
<p>Before you test it, open the <em>ViewController.h</em> file and make our class conform to the <em>UIActionSheetDelegate</em> protocol. That&#x2019;s necessary to fix the warning Xcode appears in the line where we declare <em>self</em> as the delegate of the action sheet. So, modify the interface header line as follows:</p>
<pre lang="objc">@interface ViewController : UIViewController <uiactionsheetdelegate>
</uiactionsheetdelegate></pre>
<p>Build and run the application now for first time. Click on the <strong>Normal Action Sheet</strong> button, and the action sheet will appear. Pretty nice, don&#x2019;t you think? With just a couple of lines we managed to implement an option menu and present it to the user.</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_1_normal_action_sheet.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3452" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t11_1_normal_action_sheet.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/05/t11_1_normal_action_sheet-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<p>Tap on any button you want and the action sheet will disappear. Even though it gets dismissed, for the time being we are unable to handle the tapped button. Don&#x2019;t worry about that, we&#x2019;ll fix it later on.</p>
<h2>Customizing UIActionSheet Options</h2>
<p>In the previous example, we created our first action sheet and we saw how it looks like when all of the buttons are used. However, such an action sheet might not always be suitable for every case you may encounter, and then you&#x2019;ll definitely need to adjust the displayed options only to those you desire. I already mentioned previously that you can skip a button&#x2019;s appearance if you simply set the nil value to the respective parameter value, and in this part of the tutorial we&#x2019;ll see a couple of such examples.</p>
<p>Let&#x2019;s begin working with the second button we added to the view, titled <strong>Delete Confirmation Action Sheet</strong>. Let&#x2019;s suppose that you have a table view full of contacts, and before deleting one you want to show a confirmation action sheet to the user. In that case, you would like to use a delete button to perform the actual deletion, and a cancel button just to dismiss it. This can be achieved easily, as long as you set to the <em>otherButtonTitles</em> parameter the nil value. The following IBAction implementation demonstrates exactly that (make sure you work on the <em>ViewController.m</em> file):</p>
<pre lang="objc">- (IBAction)showDeleteConfirmation:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@&quot;Really delete the selected contact?&quot;
                                                             delegate:self
                                                    cancelButtonTitle:@&quot;No, I changed my mind&quot;
                                               destructiveButtonTitle:@&quot;Yes, delete it&quot;
                                                    otherButtonTitles:nil];

    [actionSheet showInView:self.view];
}
</pre>
<p>As you see, the title of the action sheet is in accordance to the current occasion. Further than that, you see that you can set any title you wish to both the delete and cancel buttons.</p>
<p>Now, run once again the application, and tap (or click on the Simulator) on the second button. Here&#x2019;s you what you should see:</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_6_delete_confirmation_action_sheet.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3457" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t11_6_delete_confirmation_action_sheet.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/05/t11_6_delete_confirmation_action_sheet-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<p>Let&#x2019;s see now one more example. Let&#x2019;s suppose you want to present an action sheet to let users select a color among five possible values, you don&#x2019;t need of course to have a destructive button, and you don&#x2019;t want to provide a cancel button too. In this case, you have to set the nil values to both the destructive and cancel button titles, and simply provide the nil terminated string with all the colors titles. The implementation of the next IBAction method shows just that:</p>
<pre lang="objc">- (IBAction)showColorsActionSheet:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@&quot;Pick a color:&quot;
                                                             delegate:self
                                                    cancelButtonTitle:nil
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@&quot;Red&quot;, @&quot;Green&quot;, @&quot;Blue&quot;, @&quot;Orange&quot;, @&quot;Purple&quot;, nil];

    [actionSheet showInView:self.view];
}
</pre>
<p>If you run the application now, you&#x2019;ll see that only simple buttons are displayed on the action sheet, while the destructive and cancel buttons have been omitted. Here&#x2019;s a sample of what you should see on your screen when tapping on the third button:</p>
<p><img loading="lazy" decoding="async" width="247" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_7_colors_action_sheet.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3458" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t11_7_colors_action_sheet.jpg 247w, https://www.appcoda.com/content/images/wordpress/2014/05/t11_7_colors_action_sheet-164x300.jpg 164w" sizes="(max-width: 247px) 100vw, 247px"></p>
<p>Through these two examples it was made clear how you can use the provided kinds of buttons depending on your project&#x2019;s needs. It&#x2019;s amazingly easy to create a menu of options and show them to the user, make various button combinations, and as you&#x2019;ll see right next, it&#x2019;s very easy to handle the user response too. The only drawback is that you cannot modify the sheet&#x2019;s visual style, and that can consist of a prohibitive reason for not using it to customized applications.</p>
<h2>Handling Actions</h2>
<p>The <em>UIActionSheetDelegate</em> protocol we previously adopted, provides a few delegate methods that can be used in order to fully control the user response to action sheets. In this section we are going to talk about all of them, and we&#x2019;ll begin by the most commonly used one, the <em>actionSheet:clickedButtonAtIndex:</em>.</p>
<p>This method as you probably correctly guess, returns the index of the button that was tapped to an action sheet. You should always keep in mind that the index of the top most button is 0 (zero), and moving towards bottom the index gets increased by one. There will be times that you&#x2019;ll want to get the title of the tapped button instead of its index. That&#x2019;s easy to get, as the <em>actionSheet</em> parameter object supports a method named <em>buttonTitleAtIndex:</em>. Providing it simply with the tapped button index, you get the appropriate title. Also, in most of the times you&#x2019;ll probably use a <em>switch</em> or an <em>if</em> structure in order to perform the appropriate action, depending on the user response.</p>
<p>When you have just one action sheet in your view controller, then it&#x2019;s simple to handle it using this delegate method. However, when you have multiple action sheets just like here, then you must define in which one a button has been tapped. That can be achieved by setting a <em>tag</em> value to each action sheet. So, go to all three IBAction methods we previously implemented and set to each action sheet a tag value as shown below:</p>
<pre lang="objc">// showNormalActionSheet:
actionSheet.tag = 100;

// showDeleteConfirmation:
actionSheet.tag = 200;

// showColorsActionSheet:
actionSheet.tag = 300;
</pre>
<p>In the following implementation of the delegate method, we&#x2019;ll show a message in the debugger, customized depending on the displayed action sheet. Also, we&#x2019;ll log the tapped button index and its title:</p>
<pre lang="objc">-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 100) {
        NSLog(@&quot;The Normal action sheet.&quot;);
    }
    else if (actionSheet.tag == 200){
        NSLog(@&quot;The Delete confirmation action sheet.&quot;);
    }
    else{
        NSLog(@&quot;The Color selection action sheet.&quot;);
    }

    NSLog(@&quot;Index = %d - Title = %@&quot;, buttonIndex, [actionSheet buttonTitleAtIndex:buttonIndex]);
}
</pre>
<p>Test the app now. Depending on what action sheet you display and the button you tap, the respective message appears on the debugger.</p>
<p>Let&#x2019;s go back to code, and let&#x2019;s examine the rest of the delegate methods, which you may find useful in many situations during your programming life. The first one is the <em>actionSheet:didDismissWithButtonIndex:</em> method. This one works just like the previous one, but it gets called <em>after</em> the action sheet has been dismissed. The next code segment illustrates a simple use of it, where firstly we make sure that the dismissed action sheet&#x2019;s tag value equals to 300, and then display the selected color name:</p>
<pre lang="objc">-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 300) {
        NSLog(@&quot;From didDismissWithButtonIndex - Selected Color: %@&quot;, [actionSheet buttonTitleAtIndex:buttonIndex]);
    }
}
</pre>
<p>Run the app once again, and tap on the third button. Select a color and look at your debugger. You&#x2019;ll notice that the message from this method is logged with a small delay, and after the action sheet has disappeared.</p>
<p>Besides that method, there&#x2019;s also the <em>actionSheet:willDismissWithButtonIndex:</em> one. On contrary to the above delegate method, this one is called <em>before</em> the action sheet gets dismissed. Implement it and add the same code as previously:</p>
<pre lang="objc">-(void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 300) {
        NSLog(@&quot;From willDismissWithButtonIndex - Selected Color: %@&quot;, [actionSheet buttonTitleAtIndex:buttonIndex]);
    }
}
</pre>
<p>Run the application again and watch your debugger. You&#x2019;ll see that the message coming from this method is appeared before the action sheet disappears.</p>
<p>These are the delegate methods provided, but it&#x2019;s almost certain that in 98% of cases the first one is what you&#x2019;ll use.</p>
<h2>Action Sheet on iPad</h2>
<p>Up to this point, we&#x2019;ve managed to learn the basic principles regarding the UIActionSheet, and the ways the user response can be handled. Also, our implementation was limited to iPhone-style devices only, as this is our primary device target when messing around with new stuff. However, now that theUIActionSheet essentials have become known, it&#x2019;s important to see how action sheets should be treated when working on iPad devices, as things change a bit here.</p>
<p>If you ever developed for iPad, or if you are simply an iPad user, then you know that it contains a pretty nice view controller, not available on iPhone or iPod devices, the <strong>UIPopoverController</strong>. As I have already said in the introduction of the tutorial, the UIPopoverController is quite useful when it&#x2019;s necessary to show contents next to a button, cell, or anything else that has triggered an action. iPad devices are suitable for using them, as the big screen leaves enough room to display them in various sizes.</p>
<p>So, going back to our previous talk, when an action sheet is necessary to be presented to an iPad, <em>iOS encloses it into a UIPopoverController view</em>. The really important clue here is that the <em>cancel</em> button does not appear on the action sheet, because the result of that button is the same to tapping out of the popover controller; both of those dismiss popover controller/action sheet without performing any task. The existence of the cancel button would be confusing for users, so Apple engineers designed it that way so it gets removed when the target device is an iPad.</p>
<p>Apart from the above, there are also differences on the way an action sheet is shown, programmatically speaking this time. Before getting into those details though, it would be more meaningful and rewarding to see everything in practice, so let me make a turn and guide you from another path.</p>
<p>On the Project Navigator pane, click on the <em>Main_iPad.storyboard</em> file to let the iPad interface appear in the Interface Builder. Add the three buttons we added on the iPhone interface here too, as my goal is to demonstrate how similar things are handled differently in both devices. The button details:</p>
<p><em>Button #1:</em><br>
1. <strong>Title</strong>: <em>Normal Action Sheet</em><br>
2. <strong>Frame</strong>: X=313, Y=459, Width=142, Height=30</p>
<p><em>Button #2:</em><br>
1. <strong>Title</strong>: <em>Delete Confirmation Action Sheet</em><br>
2. <strong>Frame</strong>: X=270, Y=497, Width=229, Height=33</p>
<p><em>Button #3:</em><br>
1. <strong>Title</strong>: <em>Colors Action Sheet</em><br>
2. <strong>Frame</strong>: X=316, Y=535, Width=137, Height =30</p>
<p><img loading="lazy" decoding="async" width="500" height="120" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_8_ipad_ib_buttons.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3459"></p>
<p>Finish with the button preparation and then connect the existing IBAction methods to them appropriately. When you are ready, go to the <em>ViewController.m</em> file and in the implementation of the <em>showNormalActionSheet:</em> method. If you followed the steps in the previous sections of the tutorial, here&#x2019;s what it should look like:</p>
<pre lang="objc">- (IBAction)showNormalActionSheet:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@&quot;What do you want to do with the file?&quot;
                                                             delegate:self
                                                    cancelButtonTitle:@&quot;Cancel&quot;
                                               destructiveButtonTitle:@&quot;Delete it&quot;
                                                    otherButtonTitles:@&quot;Copy&quot;, @&quot;Move&quot;, @&quot;Duplicate&quot;, nil];

    [actionSheet showInView:self.view];

    actionSheet.tag = 100;
}
</pre>
<p>Run the app, but make sure to either select an iPad simulator device, or connect a real device directly. You must be watching a view similar to the next one if you tap (or click) on the first button:</p>
<p><img loading="lazy" decoding="async" width="328" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_9_ipad_default_actionsheet.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3460" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t11_9_ipad_default_actionsheet.jpg 328w, https://www.appcoda.com/content/images/wordpress/2014/05/t11_9_ipad_default_actionsheet-218x300.jpg 218w" sizes="(max-width: 328px) 100vw, 328px"></p>
<p>What you see is the default way an action sheet appears to an iPad, and as you notice the cancel button is missing. When tapping anywhere out of the popover view, you&#x2019;ll see in the debugger the message from the <em>actionSheet:clickedButtonAtIndex:</em> method, just like if you were tapping on the cancel button.</p>
<p>The way the action sheet appears is not the best possible solution, as the purpose of the popover controller is to be displayed next to the control that triggers its appearance, and even more, an arrow pointing to that control should be visible too. Very rarely, almost never one could say, an action sheet appears just like that in the centre of the screen.</p>
<p>So, what can we do to overcome this? Well, only two steps are required. The first one is to define whether the device the app works is an iPhone/iPod or an iPad. In the second case, we just have to change the way the action sheet appears on the screen. In action now, go to the IBAction method, and right below the initialization of the action sheet, add the next condition:</p>
<pre lang="objc">if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        // In this case the device is an iPad.

    }
    else{
        // In this case the device is an iPhone/iPod Touch.
        [actionSheet showInView:self.view];
    }
</pre>
<p>With the <em>UI_USER_INTERFACE_IDIOM()</em> macro you can check if you have an iPad or iPhone user interface, and ultimately follow the one or another path. In the above code, we use the <em>else</em> case to present the action sheet normally to an iPhone/iPod Touch device. </p>
<p>If you run the app now, you&#x2019;ll find out that when tapping on the first button nothing happens, and that&#x2019;s totally normal as there&#x2019;s nothing to be executed in the <em>if</em> clause. Return to the code, and add in the <em>if</em> body the next line:</p>
<pre lang="objc">[actionSheet showFromRect:[(UIButton *)sender frame] inView:self.view animated:YES];
</pre>
<p>This action sheet method accepts three parameters: The frame to be shown from, the view that it will be shown to, and a flag indicating an animating appearance or not. In our case, we want the popover controller of the action sheet to originate from the button that triggers its display, so in the <em>showFromRect</em> parameter we specify the frame of the sender button. The rest is easy. Now run the app again and tap on the first button. The result is the proper and desired one:</p>
<p><img loading="lazy" decoding="async" width="541" height="558" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_10_ipad_normal_actionsheet.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3461" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t11_10_ipad_normal_actionsheet.jpg 541w, https://www.appcoda.com/content/images/wordpress/2014/05/t11_10_ipad_normal_actionsheet-290x300.jpg 290w" sizes="(max-width: 541px) 100vw, 541px"></p>
<p>Below you are given all three IBAction methods modified appropriately, so the properly work for all devices:</p>
<pre lang="objc">- (IBAction)showNormalActionSheet:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@&quot;What do you want to do with the file?&quot;
                                                             delegate:self
                                                    cancelButtonTitle:@&quot;Cancel&quot;
                                               destructiveButtonTitle:@&quot;Delete it&quot;
                                                    otherButtonTitles:@&quot;Copy&quot;, @&quot;Move&quot;, @&quot;Duplicate&quot;, nil];

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        // In this case the device is an iPad.
        [actionSheet showFromRect:[(UIButton *)sender frame] inView:self.view animated:YES];
    }
    else{
        // In this case the device is an iPhone/iPod Touch.
        [actionSheet showInView:self.view];
    }

    actionSheet.tag = 100;
}

- (IBAction)showDeleteConfirmation:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@&quot;Really delete the selected contact?&quot;
                                                             delegate:self
                                                    cancelButtonTitle:@&quot;No, I changed my mind&quot;
                                               destructiveButtonTitle:@&quot;Yes, delete it&quot;
                                                    otherButtonTitles:nil];

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        // In this case the device is an iPad.
        [actionSheet showFromRect:[(UIButton *)sender frame] inView:self.view animated:YES];
    }
    else{
        // In this case the device is an iPhone/iPod Touch.
        [actionSheet showInView:self.view];
    }

    actionSheet.tag = 200;
}


- (IBAction)showColorsActionSheet:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@&quot;Pick a color:&quot;
                                                             delegate:self
                                                    cancelButtonTitle:nil
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@&quot;Red&quot;, @&quot;Green&quot;, @&quot;Blue&quot;, @&quot;Orange&quot;, @&quot;Purple&quot;, nil];

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        // In this case the device is an iPad.
        [actionSheet showFromRect:[(UIButton *)sender frame] inView:self.view animated:YES];
    }
    else{
        // In this case the device is an iPhone/iPod Touch.
        [actionSheet showInView:self.view];
    }

    actionSheet.tag = 300;
}
</pre>
<p>Now you know how to distinguish the device in which your app runs, and how to properly present an action sheet. Go ahead and try out all three buttons to see how the action sheet appears on iPad:</p>
<p><img loading="lazy" decoding="async" width="447" height="276" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_11_ipad_delete_confirmation.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3462"></p>
<p><img loading="lazy" decoding="async" width="450" height="396" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_12_ipad_colors_actionsheet.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3463" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t11_12_ipad_colors_actionsheet.jpg 450w, https://www.appcoda.com/content/images/wordpress/2014/05/t11_12_ipad_colors_actionsheet-340x300.jpg 340w" sizes="(max-width: 450px) 100vw, 450px"></p>
<p>You may notice that when showing the colors action sheet and then tapping out of the popover controller, the app crashes. That&#x2019;s because there is not a cancel button. To counterattack it, in the <em>showColorsActionSheet:</em> method either instead of nil set a cancel button title, or at the top of the method add the next line:</p>
<pre lang="objc">NSString *cancelTitle = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? @&quot;Cancel&quot; : nil;
</pre>
<p>and in the <em>cancelButtonTitle</em> parameter set the <em>cancelTitle</em> value. This time it will work perfectly.</p>
<h2>Action Sheet Showing Extras</h2>
<p>Until the last section of this tutorial we saw two ways for presenting an action sheet. The first one:</p>
<pre lang="objc">[actionSheet showInView:self.view];
</pre>
<p>works on all devices, while the next one:</p>
<pre lang="objc">[actionSheet showFromRect:[(UIButton *)sender frame] inView:self.view animated:YES];
</pre>
<p>has effect only on iPad. Further than those two methods, there are a few more that I consider as a good idea I should refer to, so let&#x2019;s give them a quick look.</p>
<p>The first method we&#x2019;ll talk about, is the <em>showFromTabBar:</em>, which as you guess is useful when there is a tab bar in your application. It mostly works on iPhone/iPod Touch devices, and its purpose is to allow an action sheet to properly appear without get overlapped by the tab bar. Actually, the action sheet originates from it and not from the view&#x2019;s bottom side. On iPad the action sheet will simply appear on the centre of the screen, without any arrow pointing to some point.</p>
<p>Similar to the above is the <em>showFromToolbar:</em> method. It&#x2019;s used when a toolbar exists at the bottom side of the view, and the action sheet must be properly shown without be overlapped by the toolbar.</p>
<p>Finally, there&#x2019;s also the <em>showFromBarButtonItem:animated:</em> method, which is helpful on iPad for displaying an action sheet with its popover view pointing to the bar button item that triggered the appearing.</p>
<p>As you see, there are methods suitable for iPhone devices, and methods suitable for iPad devices. However, this doesn&#x2019;t mean that they cannot be used the other way round. On iPhone, all methods have the same result and the action sheet is shown from the bottom side of the screen, or from the tab bar/toolbar. On iPad methods that do not display the popover with the action sheet to a specific place with a pointing arrow, they just show it to the centre of the screen. When displaying action sheets, always make sure that you use the appropriate method for presenting them so as to make sure that you are aligned to the recommended interface guidelines.</p>
<h2>Working with UIPopoverController</h2>
<p>Now that we have talked about action sheets and how they are displayed on both iPhone and iPad devices, let&#x2019;s do some more discussion about the UIPopoverController. Until now we referenced it a lot of times, but still we haven&#x2019;t made any implementation that allow us to manually create and show one. So, in this part we will see how it can be used in general cases, as the purpose of its existence lies to usages other than simply displaying action sheets.</p>
<p>The great with the popover controller is that it can display the contents of any view controller to the position you define, usually near the button that triggers its appearance. It can get any size you want, and the arrow that points to the button that originates from, along with the fade effect, result to a very fancy, convenient and useful tool for presenting content on top of other content when working on iPad.</p>
<p>We will see how popover controller works through a practical example. We will use a new view controller and we will display its contents in the popover. This view controller will contain a sample user data form, where some basic info can be filled in and selected (user name, age range and gender). The following Interface Builder screenshot will make it more clear:</p>
<p><img loading="lazy" decoding="async" width="432" height="492" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_13_ib_data_entry.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3464" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t11_13_ib_data_entry.jpg 432w, https://www.appcoda.com/content/images/wordpress/2014/05/t11_13_ib_data_entry-263x300.jpg 263w" sizes="(max-width: 432px) 100vw, 432px"></p>
<p>Also, the view controller will have its own <em>xib</em> file with the interface designed in it, which will be called upon initialization. Finally, through the implementation of a protocol and a delegate method we&#x2019;ll get the entered/selected data from the new view controller back to the normal one.</p>
<p>To focus on the important stuff, we won&#x2019;t manually create the new view controller. Instead, please go ahead to <a href="https://dl.dropboxusercontent.com/u/2857188/TestViewController.zip?ref=appcoda.com">download the related files</a> now, and add them to the project. Make sure you add all of the following files:</p>
<ul>
<li>TestViewController.h</li>
<li>TestViewController.m</li>
<li>TestViewController.xib</li>
</ul>
<p>Supposing at this point that you have downloaded and added all files and you are ready to proceed, let&#x2019;s create a new button to the iPad interface. Click on the <em>Main_iPad.storyboard</em> file, and let Interface Builder appear. Then, get a UIButton from the Object Library, and set the next properties:</p>
<ol>
<li><strong>Frame</strong>: X=310, Y=239, Width=149, Height=30</li>
<li><strong>Title</strong>: <em>User Data Entry Form</em></li>
</ol>
<p>After that, open the <em>ViewController.h</em> file, and declare the following IBAction method:</p>
<pre lang="objc">- (IBAction)showUserDataEntryForm:(id)sender;
</pre>
<p>Return to the Interface Builder, and connect that action method to the newly added button.</p>
<p>Now, open once again the <em>ViewController.h</em> file, and firstly import the <em>TestViewController</em> class as shown below:</p>
<pre lang="objc">#import &quot;TestViewController.h&quot;
</pre>
<p>Also, make the <em>ViewController</em> class conform to the <em>TestViewControllerDelegate</em> protocol by adding it to the interface header line like below:</p>
<pre lang="objc">@interface ViewController : UIViewController <uiactionsheetdelegate, testviewcontrollerdelegate>
</uiactionsheetdelegate,></pre>
<p>By adopting the above protocol, we&#x2019;ll be able to use the delegate method of the <em>TestViewController</em> class later on and to get the entered data.</p>
<p>Now, let&#x2019;s go to the most essential part of this section, to the implementation of the IBAction method we previously declared and to the usage of the popover controller. For starters though, we must declare a private class property for the popover, so open the <em>ViewController.m</em> and go to the private section of the interface. In there, add the following property declaration:</p>
<pre lang="objc">@interface ViewController ()

@property (nonatomic, strong) UIPopoverController *userDataPopover;

@end
</pre>
<p>Now, move straight ahead to the IBAction method implementation, where we will initialize and use the above object. As I already said in the beginning of this section, the special characteristic of the popover controller is the ability to display the contents of another view controller, therefore the first step we must make is to initialize an object of the <em>TestViewController</em> class.</p>
<pre lang="objc">- (IBAction)showUserDataEntryForm:(id)sender {
    TestViewController *testViewController = [[TestViewController alloc] initWithNibName:@&quot;TestViewController&quot; bundle:nil];
    testViewController.delegate = self;

}
</pre>
<p>As you see, upon initialization we load the view controller&#x2019;s xib file as well, and beyond that, we make our class the delegate of the <em>testViewController</em> object. Now that we have a view controller on our hands, let&#x2019;s use the popover controller object we privately declared and let it finally appear. We only need to add three commands, which we&#x2019;ll see step by step. Initially, let&#x2019;s perform the initialization:</p>
<pre lang="objc">self.userDataPopover = [[UIPopoverController alloc] initWithContentViewController:testViewController];
</pre>
<p>It&#x2019;s obvious that the view controller we want to display is directly given as a parameter to the popover controller. That&#x2019;s why we first declared and initialized the <em>TestViewController</em> object. The next step is to define the popover size, which usually matches the contained view&#x2019;s size:</p>
<pre lang="objc">self.userDataPopover.popoverContentSize = CGSizeMake(320.0, 400.0);
</pre>
<p>Finally, let&#x2019;s display it:</p>
<pre lang="objc">[self.userDataPopover presentPopoverFromRect:[(UIButton *)sender frame]
                                       inView:self.view
                     permittedArrowDirections:UIPopoverArrowDirectionAny
                                     animated:YES];
</pre>
<p>This method accepts four parameters as you can notice. The first one is the frame from which the popover originates, and usually is the button&#x2019;s frame that is used to present it. The next one, is the view in which the popover controller will appear to. As you understand, it&#x2019;s not always necessary to display it in the default view, but that&#x2019;s the most common case. The third parameter specifies the direction of the arrow that appears on the popover controller, pointing to the button that originates from. Unless you make sure that the popover controller will always be displayed on the same place, then you&#x2019;d better use <em>UIPopoverArrowDirectionAny</em> parameter to allow the system decide the position of the arrow. Don&#x2019;t forget that when changing iPad&#x2019;s orientation the popover controller can be re-positioned to a new place, and is quite possible that the arrow should point towards another direction. Finally, the last parameter specifies whether the popover will appear using animation or not, and usually that value is set to YES.</p>
<p>Here&#x2019;s the whole IBAction method:</p>
<pre lang="objc">- (IBAction)showUserDataEntryForm:(id)sender {
    TestViewController *testViewController = [[TestViewController alloc] initWithNibName:@&quot;TestViewController&quot; bundle:nil];
    testViewController.delegate = self;

    self.userDataPopover = [[UIPopoverController alloc] initWithContentViewController:testViewController];
    self.userDataPopover.popoverContentSize = CGSizeMake(320.0, 400.0);
    [self.userDataPopover presentPopoverFromRect:[(UIButton *)sender frame]
                                       inView:self.view
                     permittedArrowDirections:UIPopoverArrowDirectionAny
                                     animated:YES];


}
</pre>
<p>If you give the app a try now, then when tapping on the new button existing on the interface you&#x2019;ll see the popover controller appearing and containing the <em>TestViewController</em> interface. Cool and fast way to show some content, right?</p>
<p><img loading="lazy" decoding="async" width="438" height="450" src="http://www.appcoda.com/wp-content/uploads/2014/05/t11_2_uipopovercontroller_example.jpg" alt="Introduction to UIActionSheet and UIPopoverController" class="aligncenter size-full wp-image-3453" srcset="https://www.appcoda.com/content/images/wordpress/2014/05/t11_2_uipopovercontroller_example.jpg 438w, https://www.appcoda.com/content/images/wordpress/2014/05/t11_2_uipopovercontroller_example-292x300.jpg 292w" sizes="(max-width: 438px) 100vw, 438px"></p>
<p>Back to code now, let&#x2019;s implement the delegate method of the <em>TestViewController</em> class, in which we&#x2019;ll simply log on the debugger the entered and selected data, and the we will dismiss the popover controller. There&#x2019;s nothing especially hard in it, so here I give you its implementation:</p>
<pre lang="objc">-(void)userDataChangedWithUsername:(NSString *)username andAgeRange:(NSString *)ageRange andGender:(NSString *)gender{
    NSLog(@&quot;Your name is %@, your age range is %@ and your gender is %@&quot;, username, ageRange, gender);

    [self.userDataPopover dismissPopoverAnimated:YES];
}
</pre>
<p>Run the app once again now. You&#x2019;ll find out that the Done button properly works, and on the debugger you see all the data you entered on the form. Also, the popover controller gets disappeared from the screen.</p>
<p>In most of cases, what you read in here is the way that you&#x2019;ll need to use the popover controller. The &#x201C;hard&#x201D; thing is to prepare the view controller that it will be contained, along with all the logic behind it, not the popover itself. However, in the rare cases you might need to use delegate methods, first make sure that your class conforms to the <em>UIPopoverControllerDelegate</em>, and then proceed to the implementation. The provided delegates methods are:</p>
<ol>
<li><em>popoverControllerShouldDismissPopover:</em> This one is called before the popover controller disappears from the screen.</li>
<li><em>popoverControllerDidDismissPopover:</em> This one is called after the popover controller has disappeared from the screen.</li>
</ol>
<p>Use any, or both of them depending on your needs.</p>
<h2>Summary</h2>
<p>Reaching the end of this tutorial, it becomes clear that using action sheets and popover controllers consist of a very easy, fast and convenient way to present menus and content to the user. The great common element on both of them, is the fact that they can be presented almost instantly, with a little effort. The only drawback is that they may do not fit to the ecosystem on highly customized applications, but that&#x2019;s something that developers know from the beginning. Closing, in case you don&#x2019;t use any or both of these view controllers, I would advise you to start doing so, as they are time-saving tools and even more, it&#x2019;s possible to make your apps look even more professional. Happy&#x2026; action-taking!</p>
<p>For your reference, you can <a href="https://dl.dropboxusercontent.com/u/2857188/ActionSheetDemo.zip?ref=appcoda.com">download the complete Xcode project from here</a>. Again, leave me comment if you have any questions.</p>

<!--kg-card-end: html-->
]]></content:encoded></item></channel></rss>