40

How can I get instance of current UIApplication from View Controller in Swift?

I am getting Use of unresolved identifier 'sharedApplication' error with this code:

let app = sharedApplication as UIApplication
Evgenii
  • 36,389
  • 27
  • 134
  • 170

2 Answers2

75

EDIT Swift 4.x

let app = UIApplication.shared.delegate as! AppDelegate

If you're e.g. not in a ViewController, you must:

import UIKit

Perhaps try:

let app = UIApplication.sharedApplication()

EDIT (Swift 3):

It should be noted that in Swift 3, to accomplish this, you will want to access the shared property instead:

let app = UIApplication.shared
Jon Winstanley
  • 23,010
  • 22
  • 73
  • 116
Darren
  • 1,682
  • 1
  • 15
  • 33
11

You can do it by

let app =  UIApplication.sharedApplication()
iPatel
  • 46,010
  • 16
  • 115
  • 137