iOS Interview Questions And Answers

iOS Interview Questions And Answers

What is a memory leak?

A memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. In object-oriented programming, a memory leak may happen when an object is stored in memory but cannot be accessed by the running code.

Describe what “app thinning” means?

The store and operating system optimize the installation of iOS, tvOS, and watchOS apps by tailoring app delivery to the capabilities of the user’s particular device, with minimal footprint. This optimization, called app thinning, lets you create apps that use the most device features, occupy minimum disk space, and accommodate future updates that can be applied by Apple.

What is auto-layout?

Auto Layout dynamically calculates the size and position of all the views in your view hierarchy, based on constraints placed on those views.

What is GCD? How is it used?

GCD is the most commonly used API to manage concurrent code and execute operations asynchronously at the Unix level of the system. GCD provides and manages queues of tasks. A good example is when an App fetch data from an API, this network call should be done in a background thread and the display of the data in the view should be executed in the main thread as well as any UI updates.

What are the benefits of Swift over Objective-C ?

  • Swift is easier to read. (mmm really?)
  • Swift is easier to maintain.
  • Swift is safer.
  • Swift is unified with memory management.
  • Swift requires less code.
  • Swift is faster.
  • Fewer name collisions with open source projects.
  • Swift support dynamic libraries.
  • Swift Playgrounds encourages interactive coding.
  • Swift is a future you can influence.

Here is a link where you can see these assertions in detail.

What is Synchronous vs. Asynchronous in GCD ?

These terms describe when a function will return control to the caller, and how much work will have been done by that point.

A synchronous function returns only after the completion of a task that it orders.

An asynchronous function, on the other hand, returns immediately, ordering the task to be done but not waiting for it. Thus, an asynchronous function does not block the current thread of execution from proceeding on to the next function.

Why do you generally create a weak reference when using self in a block?

To avoid retain cycles and memory leaks.

What is the GCD method you call to pass some work to a queue asynchronously? What parameters do you provide to this method?

dispatch_async(dispatch_get_main_queue(), ^{ });

We pass as a parameter the dispatch queue where we want to execute the code.

What are some ways to support newer API methods or classes while maintaining backward compatibility? For instance, if you want your view to have a red tintColor (a method introduced in iOS 7), but your app still supports iOS 6, how could you make sure it won’t crash when running on iOS 6? Another example would be using NSURLSession vs. NSURLConnection — how could you make it so that your code uses the most appropriate of those two classes?

  • Treat deprecated APIs warnings as errors to resolve.
  • At runtime, check for OS versions.
  • objC : Mark legacy code paths with macros.

if #available(iOS 8, *, *) {

self.view.convertPoint(.Zero, toCoordinateSpace:anotherView)

} else {

self.view.convertPoint(CGPointZero, toView:anotherView)


Control the number of 3d party libraries.

You can see this topic in more detail here.

What is MVC ?

MVC is a design pattern that stands for model view controller, this design pattern separates the data from its display, mediated by a View Controller.

What are delegates ?

Delegates are a design pattern. A delegate is just an object that another object sends messages to when certain things happen so that the delegate can handle app-specific details the original object wasn’t designed for. It’s a way of customizing behavior without subclassing. And it’s important to remember that they have one to one relationship.

What are NSNotificationCenter and how does it work ?

NSNotificationCenter is what Apple has provided as an Observer Pattern in the Cocoa library . The basic idea is that a listener registers with a broadcaster using some predefined protocol. At some later point, the broadcaster is told to notify all of its listeners, where it calls some function on each of its listeners and passes certain arguments along. This allows for asynchronous message passing between two different objects that don’t have to know about one another, they just have to know about the broadcaster.

What is Core Data ?

Core Data is not an ORM or object-relational mapper. Nor is it a database. Instead, Core Data is an object graph manager which also has the ability to persist object graphs to a persistent store, on a disk.

What is a managed object context ?

A managed object context represents a single object space, or scratch pad, in a Core Data application.

Difference between frame and bounds ?

The frame relates a view’s location and size in its parent View.

The bounds relate a view’s location and size using its own coordinate system.

What is the purpose of the reuseIdentifier ?

Reusability of an already allocated object.

How many UITableViewCells are allocated when you first load a UITableView? How many additional ones are allocated as you scroll through the table?

A UITableView will normally allocate just enough UITableViewCell objects to display the content visible in the table. Because of the reuseIdentifier , the UITableView will not allocate new UITableViewCell objects for each new item that scrolls into view, avoiding laggy animations.

Define atomic and nonatomic.

Atomic is the default: if you don’t type anything, your property is atomic. An atomic property is guaranteed that if you try to read from it, you will get back a valid value. It does not make any guarantees about what that value might be, but you will get back good data, not just junk memory. What this allows you to do is if you have multiple threads or multiple processes pointing at a single variable, one thread can read and another thread can write. If they hit at the same time, the reader thread is guaranteed to get one of the two values: either before the change or after the change. What atomic does not give you is any sort of guarantee about which of those values you might get. Atomic is really commonly confused with being thread-safe, and that is not correct. You need to guarantee your thread safety other ways. However, atomic will guarantee that if you try to read, you get back some kind of value.

On the flip side, non-atomic, as you can probably guess, just means, “don’t do that atomic stuff.” What you lose is that guarantee that you always get back something. If you try to read in the middle of a write, you could get back garbage data. But, on the other hand, you go a little bit faster. Because atomic properties have to do some magic to guarantee that you will get back a value, they are a bit slower. If it is a property that you are accessing a lot, you may want to drop down to nonatomic to make sure that you are not incurring that speed penalty.

If you want to know more about this check this article

Whats the difference between weak and strong ?

These keywords are related to reference counting and “denote ownership”, if you will. They help you eliminate retain-release cycles by limiting what objects increment the reference count for another object. A strong property is one where you increment the reference count of the object. If object A has a strong reference to B, and no other object is referencing B, B has count 1 (A owns, or needs to exist B). Now, if B wants to have a reference to A, we would want to use a weak reference. Weak references don’t increment the reference count of the object. So in this particular case, if A has no other objects referencing it but B, A’s count would be 0 given B’s weak reference.

What’s the difference between not-running, inactive, active, background and suspended execution states?

  • Not running: The app has not been launched or was running but was terminated by the system.
  • Inactive: The app is running in the foreground but is currently not receiving events. (It may be executing other code though.) An app usually stays in this state only briefly as it transitions to a different state.
  • Active: The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.
  • Background: The app is in the background and executing code. Most apps enter this state briefly on their way to being suspended. However, an app that requests extra execution time may remain in this state for a period of time. In addition, an app being launched directly into the background enters this state instead of the inactive state.
  • Suspended: The app is in the background but is not executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, an app remains in memory but does not execute any code. When a low-memory condition occurs, the system may purge suspended apps without notice to make more space for the foreground app.

What is a category and when is it used ?

A category is a way of adding additional methods to a class without extending it. It is often used to add a collection of related methods. A common use case is to add additional methods to built-in classes in the Cocoa frameworks.

View story at


Swift UITableView: Load data from JSON

In this tutorial I’ll explain you how to fill an iOS UITableView component by loadingthe data directly from an URL using the JSON format. You’ll see how to define a tableview controller in swift, how to load the data from URL and how to extract the data from the JSON format.

Define the project

Let’s create a new Swift iOS single view project.


In the Main.storyboard you can disable the use size classes option.


Now you can remove the View controller that is inside the storyboard as default, we don’t need that!


Define the layout and the custom classes

In the Main.storyboard you’ve to add the UITableViewController element.


Now you’ve to set a custom class for the UITableViewController that allows you to manage the data that will be displayed.

Create a new iOS Cocoa Touch Class and set the subclass asUITableViewController and the name of the class as TableController and create it.

Swift: add custom class


Now in the Main.storyboard select again your UITableViewController and in the identity inspector set the TableController class that you’ve prevously created.

Swift: set custom class


In the Attribute inspector turn on the is initial view controller option.

Swift: is initial controller


Now you have to select the table view cell and under the attribute inspector set the identifier to cell.

Swift: cell identifier


TableController custom class

Now you’ve to implement the table controller class. This class is the core of the table. Here you’ll define the download function, the json extractor function and finally the cell definition.

The first thing you’ve to do is to define the array that will be used to store and read the data. Let’s define the TableData String array as:

var TableData:Array< String > = Array < String >()

The viewDidLoad() is the function that will be called as soon as the view has been loaded. Inside it you should call the get_data_from_url function. We will define this function later, but let’s add the function call placeholder.

var TableData:Array< String > = Array < String >()
override func viewDidLoad() {

At this link I’ve prepared for you a json object. This is a simple list of countries and countries’ codes. If you want use this easy tool to explore this structure in a readable format.

Set the number of sections to 1 and the number of rows to the array’s size.

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
     return 1
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return TableData.count

Configure now the cell to load the array string at the position defined by the indexPath object. The “cell” identifier is the same identifier name that you previously set for the cell element. The cellForRowAtIndexPath function is called for every cell that is visible on the screen at a particular moment. So, for example, if you have to load 200 cells on your table, this function is called only 10-15 times, that’s because only the elements that have to be displayed are loaded. Every time you scroll your table, this function is called again for the items that have to be displayed.
In this case we’ll use the textlabel that is defined in the default cell layout.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
     cell.textLabel?.text = TableData[indexPath.row]
     return cell

let’s define now the get_data_from_url function by exploiting theiOS asynchronous call.

func get_data_from_url(url:String)
    let httpMethod = "GET"
    let timeout = 15
    let url = NSURL(string: url)
    let urlRequest = NSMutableURLRequest(URL: url!,
    cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
    timeoutInterval: 15.0)
    let queue = NSOperationQueue()
                                  queue: queue,
                                  completionHandler: {(response: NSURLResponse!,
                                                                   data: NSData!,
                                                                   error: NSError!) in
             if data.length > 0 && error == nil{
             }else if data.length == 0 && error == nil{
                 println("Nothing was downloaded")
             } else if error != nil{
                 println("Error happened = \(error)")

When the get_data_from_url function has done the download of the json data, the extract_json function is called. Let’s now implement it. This function will extract the json data and fill the TableData array. In a JSON format there are two different main types: the array and the objects. Arrays are identified by the [ ] brackets while the object are identified by the { } brackets. This two types in Swift are defined by NSArray and NSDictionary respectively. For every JSON object you’ve to define a safe variable (using let and the question mark) with the right type. The json used in this example has this structure:

name (String)
code (String)

name (String)
code (String)

Let’s now implement the extract_json function.

func extract_json(jsonData:NSData)
     var parseError: NSError?
     let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError)
     if (parseError == nil)
        if let countries_list = json as? NSArray
           for (var i = 0; i < countries_list.count ; i++ )
               if let country_obj = countries_list[i] as? NSDictionary
                   if let country_name = country_obj["country"] as? String
                       if let country_code = country_obj["code"] as? String
                             TableData.append(country_name + " [" + country_code + "]")


Finally we have the data into our TableData array, we only have to refresh the table in the main thread.

func do_table_refresh()
     dispatch_async(dispatch_get_main_queue(), {


You can download the code for this example here.
UPDATE: download the swift 2 code example from here

Swift: TableView tutorial

Reference Reference

Remote JSON Data to tableView in iOS (Swift)

import UIKit
import Foundation
import XCPlayground


class RemoteAPI {
    func getData(completionHandler: ((NSArray!, NSError!) -> Void)!) -> Void {
        let url: NSURL = NSURL(string: "")
        let ses = NSURLSession.sharedSession()
        let task = ses.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
            if (error != nil) {
                return completionHandler(nil, error)

            var error: NSError?
            let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
            if (error != nil) {
                return completionHandler(nil, error)
            } else {
                return completionHandler(json["results"] as [NSDictionary], nil)

var api = RemoteAPI()

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var tableView: UITableView!
    var items: NSMutableArray = []
    override func viewDidLoad() {
        self.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480)
        self.tableView = UITableView(frame:self.view!.frame)
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        api.getData({data, error -> Void in
            if (data != nil) {
                self.items = NSMutableArray(array: data)
            } else {
                println("api.getData failed")
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
        if let navn = self.items[indexPath.row]["trackName"] as? NSString {
            cell.textLabel.text = navn
        } else {
            cell.textLabel.text = "No Name"
        if let desc = self.items[indexPath.row]["description"] as? NSString {
            cell.detailTextLabel.text = desc
        return cell



import UIKit

class TableViewController: UITableViewController {

var tableName = [String]()
var tableID = [String]()
override func viewDidLoad() {


override func didReceiveMemoryWarning() {
    // Dispose of any resources that can be recreated.

func getContactListJSON(){
    let urlString = ""
    let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
    let url = NSURL( string: urlEncodedString!)
    var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
        let json = JSON(data: data)
        let contactsArray = json.arrayValue

        dispatch_async(dispatch_get_main_queue(), {
            for contacts in contactsArray
                let id = contacts["id"].stringValue
                let name = contacts["name"].stringValue
                println( "id: \(id) name: \(name)" )

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tableName.count

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell

    // Configure the cell... = tableID[indexPath.row] = tableName[indexPath.row]
    return cell


How to Pass Data Between iOS Views in Swift

This tutorial will walk you through the process of passing data from one view to another in an iOS 8 application using Swift. Let’s get started!

There are a few steps to the process but once done you will see it is pretty simple to do provided you get everything in place. I am going to step over a few of the details that I think by now you should be familiar with like creating a new project, outlets and actions. If these are still a little new to you I strongly recommend looking through some of my other articles that cover those topics and more

First create a new Swift based iOS project with a single view to keep the code base to a minimum and allow us to focus on the details we are really interested in.


Rz Rasel

Now create a second view controller by searching and dragging one from the object library (lower right panel, third icon). We will pass two simple strings between the views, so for the first view controller add two text entry fields and a button. For the second add two labels which will display the text you enter on the first view.

02 - Two view controllers with controls.

To pass the data and change views we use a segue to move between these two views (I have added an extra step here incase I want to do anything extra when the button is clicked), right click the button and drag to the second view controller and release. From the popup menu select Action Segue > show, this sets up the segue to take place when the button is pressed. See the video below if you need extra help to make sense of it.

Click Here to View Video – Creating segue between view controllers.

Make sure you are using the first view controller and open the assistant editor (second icon on the right hand side of the xcode icon bar, it looks like a jacket and bow tie), you should see the view controller.swift file appear. Right click and drag from the first text entry field to the controller code and create an @IBOutlet named ‘fieldA’, then do the same with the second text entry field and name it ‘fieldB’. I also added an @IBAction for the button but it is not needed for the segue to take place, I just added it in case I want to do some extra things when it is clicked. The code for the view controller should now look something like this.

04 - First View Controller with Outlets and Action.

The icon that you see between the two views is called a segue, you will most likely end up using more than one in an application so for that reason I strongly recommend naming them all so they can be uniquely identified in code. So go ahead and click on the segue icon and in the right hand side attributes view give it the name ‘btnSubmitSegue’ as seen in the screenshot below.

05 - Segue Identifier

For the second view controller we are going to create our own UIViewController class as the one provided has a lot of code that you just do not need to be confused with at this time! So in the file menu create a new iOS Cocoa Touch Class.

06 - New iOS Cocoa Touch Class

I named my class ‘SecondViewController’, make sure you have the language set to Swift.

07 - SecondViewController Class Creation

Next we need to assign our new custom view controller class to our view, to do that select the second view controller and in the right hand identity inspector panel under ‘Custom Class’ in the field named ‘Class’ enter the name of the file you just created, in my case ‘SecondViewController’, you should notice as you start typing it that auto complete will try and help you out. A little side tip here is that Xcode is great at trying to help you complete many things, so if you find auto complete is not working then it might be a sign you got something wrong.

08 - Second View Controller with custom Class

The assistant editor for the second view controller should now be showing the nice clean version of our new class file. Right click on the labels in the view one by one and drag to the code window to create two new @IBOutlets called labelA and labelB. These will be used to reference the text labels on the view and populate them with the entries from the first screen.

09 - Second View Controller with Outlets

Now we need to add some properties to our second view controller class so that we can assign our data from the first view during the segue and hand it off to the new view. To do that create two variables, see the screenshot below. For simplicity I called my two variables (one per display label) ‘dataPassed’ and ‘secondDataPassed’.

10 - Second View Controller Class with Outlets and Variables

Now the next step (yes I know it seems like a lot of steps!) is to create code that assigns the entry field text to our variables in the second view, we do this by overriding something calledprepareForSegue. As the name suggests we are overriding the default with our code, copy and paste or enter the code below in ‘ViewController.swift’ and see the screenshot for reference.

11 - Segue Code

Finally! In our second view controller class file (secondViewController.swift) we need to assign the variables to the display labels when the viewDidLoad is called. This is straight forward, just look for the override func viewDidLoad() and enter the code below (again see screenshot for reference).

12 - Second View Controller with assignment code

We are done! You have reached the rainbow, run the simulator and enter some text into the two fields then hit the button, the second view should load showing the text you entered.

Click Here To View Video – Testing The Application

Hopefully this has cleared up some of the mystery for you and set you on a path to multi-view happiness!

I have included a link to a sample project

iOS Swift Tutorial – passing data between ViewControllers

Since Apples spectacular WWDC announcement of a new programming language Swift, I have been super excited to learn this new language, so like many, I grabbed the beta version of Xcode 6 and started coding!

A question I have been asked a lot by people relatively new to iOS development is “how do I pass data/variables between ViewControllers in Swift?”, this short tutorial aims to show you exactly that.

We’re not creating a super fancy app here, just a simple app that takes some data and passes it through to the next ViewController via the prepareForSegue method, straightforward right? lets get to it.

1. Lets start by creating a single view application in Xcode 6, make sure to select Swift as the language for the project.

Step 1 - Create single view application

2. Create a new class file called ‘secondViewController’ and link it up to a new view controller in the story board, I am not going to go into detail in this post as I am assuming a basic knowledge of Xcode.

– Note, I am not sure if this is a bug with the beta version templates but you may want to comment out this code in the secondViewController else you will have an error when you run your app!

3. Next up, add a text field and a button to the main ViewController and a label to the secondViewController and link them to the classes in the usual fashion, I have called my text field ‘textField’ and the label in secondViewController ‘labelPassedData’ which is of course where the data will be displayed.

Screen Shot 2014-06-28 at 21.24.44

4. Now we need to set up the segue – to do this, head back over to the storyboard and whilst holding down the CTRL key click the button and drag over to the second ViewController, you should then see this appear.

iOS Swift segue popup

You need to select show.

5. Now you should see an arrow line joining up the 2 ViewControllers, click on this and in the right panel attributes inspector you will see the option for an identifier, lets call it segueTest

iOS Swift segue identifier

6. Awesome – now for some coding! – head over to ViewController.swift and add this code under the ‘didReceiveMemoryWarning’ function

iOS swift - Xcode

7. You should now have an error up, this is due to secondViewController not having a property declared called toPass so lets go and add this to our secondViewController

This just adds the variable (or property) to the class and the exclamation mark just lets the class know that a value will be assigned to it – your error on ViewController.swift should now disappear.

8. In the secondViewController under the viewDidLoad function add this code

9. Thats it! run the app, type some text in the field once the button is pressed, the next view should appear with your previously typed value.

I hope you enjoyed this tutorial and found it useful, this is my first Swift tutorial and I have many more planned so be sure to share on your favourite social networks and let me know in the comments below how you are getting on with Swift!

Make a simple popup window in iOS SDK (Swift)

I was asked to create a simple popup window on a project I’m currently working on and I haven’t found any nice implementation of a clean popup window with the iOS SDK.

import UIKit

class PopUpViewControllerSwift : UIViewController {
 @IBOutlet weak var popUpView: UIView!
 @IBOutlet weak var messageLabel: UILabel!
 @IBOutlet weak var logoImg: UIImageView!
 override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
 super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

 required init?(coder aDecoder: NSCoder) {
 super.init(coder: aDecoder)
 override func viewDidLoad() {
 self.view.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height) //sets the
 self.view.backgroundColor = UIColor.clearColor()
 self.popUpView.layer.cornerRadius = 5
 self.popUpView.layer.shadowOpacity = 0.8
 self.popUpView.layer.shadowOffset = CGSizeMake(0.0, 0.0)
 @IBAction func closePopup(sender: AnyObject) {
 self.dismissViewControllerAnimated(true, completion: nil)

Create a auto hide popup with swift

Mar 05, 2015 19:401

So i needed a popup kind of view for an IOS app. The purpose of the popup was to display a message when a gesture action has taken place. Gestures can be confusing for people and for complex gesture its better to show some kind of message so that user knows that something happened. Here is the code.

1) Take a ViewController. Add a button and a UIVIew on it. In the UIView add a label. This label can be changed based on the message that needs to be passed.
Screenshot at Mar 05 19-44-25

2) In the view controller we add our code.  Code has 2 methods.  On button click i am displaying the popup and triggering a timer.  2nd method gets called when the timer is over. In the 2nd method i hide the popup with animation.


Display a popover in Swift

On my first project i needed a popup style presentation that would have worked on iPhone and iPad.
In swift we have the UIPopoverPresentationController to deal with that need.


First you need a ViewController that will be the view of your popover. You can built it in the storyboard or in code.
If its in a storyboard you will access it in code with something like that :

If you built it in code your variable setting will look like something like that :

Then you give it the .Popover modalPresentationStyle and define its preferred size :

And now the tricky part begins, you will need to present your controller and for that configure the popoverPresentationController.
For that task you need to conform to theUIPopoverPresentationControllerDelegate protocol, and your ViewController class will look like :
class ViewController: UIViewController,
UIPopoverPresentationControllerDelegate {

then you setup your presentation controller and present it :

In that example the popover is called from a tapGesture Selector, the location variable is the location of the tap recovered from the Gesture recognizer. If you access your popover from a BarButtonItem you should look at the.presentPopoverFromBarButtonItem property.
In order to work on iPad you need to set the sourceView and the sourceRect (here the sourceView is the view from witch the tapGesture occurs, if you come from a Button the sender will be that button.)

In iOS 8 we have the opportunity to present the popover with the same behavior of an iPad (in popup and not in a modal fullscreen view controller). For that purpose you need to add that method of the protocol :

Et voila !


popup dialog box in Swift iOS

popup box in Swift iOS

Popup dialog box in Swift iOS was easy before, in case you’re wondering how it’s done now,  here is a simple code that works.

Apple is changing the development standards/method from time. For now this works,  but who knows for how long. Just copy the code and put it where it needs to go.


override func viewDidAppear(animated: Bool) {
var alert = UIAlertController(title: “Alert”, message: “Message”, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: “Click”, style: UIAlertActionStyle.Default, handler: nil))
alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
textField.placeholder = “Enter text:”
textField.secureTextEntry = true
self.presentViewController(alert, animated: true, completion: nil)


iOS SDK: Pop up window in Swift


One of the most popular posts in my blog is the tutorial for creating a Pop-up window with iOS SDK using Objective-C. Since then many readers reached me out asking for a Swift version of the Pop-up. In general the process is exactly the same in Swift (except the language used to write the code of course…), so I am not going to dive into the process of creating the .xib files again. For this you can always refer to the original post.

The Pop-up controller is a subclass of UIViewController with a couple of methods for the fade in and fade out animations.

In the viewDidLoad method, I styled the PopUp with rounded corners. You can customize that for square corners or other shadow styles. Note that in Swift we have to implement also the required init(coder aDecoder: NSCoder) and as we’ve created the UI in interface builder using .XIBs the override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) method has to be added too. Add these two methods and we are almost done:

Now that the PopUp is implemented, we have to call it from the view where we want to display it.

A fully working example alongside with the Objective-C and Swift code for the PopUp is available on Github. Feel free to use it in your projects and if you find any issue or glitch, do not hesitate to open an issue on Github.

A video version of the tutorial is provided by Webucator.