0

I'm using Swift and the newest Xcode version.

I have this code in AppDelegate.swift:

func testPrint(string: String) {
    print(string)
}

I can successfully call the function from the file ViewController.swift like this:

let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.testPrint(string: "Hello!")

But if I'm trying to call the function from TodayViewController.swift, which is for Apples Today Extension, I'm getting the following error:

Use of undeclared type 'AppDelegate'

Why that?

1 Answers1

1

Try something along those lines:

let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.testPrint(string: "Hello!")

EDIT: 'Today Extension' and App live in a different contexts so it is not possible.

Adam
  • 1,054
  • 1
  • 12
  • 26
  • I'm getting `Use of undeclared type 'AppDelegate'`. –  Aug 09 '18 at 16:46
  • What version of Swift do you use? – Adam Aug 09 '18 at 16:48
  • If I'm trying to call the function with your code from `ViewController.swift` it's working. It's not working from `TodayViewController.swift` which is for Apples `Today Extension`. Any idea how? Is there something special if a file belongs to `Today Extension`? –  Aug 09 '18 at 16:50
  • show the whole code please – Adam Aug 09 '18 at 16:52
  • I updated my question. There isn't more code that matters for this case. –  Aug 09 '18 at 16:56
  • Ahh, 'Todays extension' is not an application so it does not have AppDelegate. What is it exactly you are trying to achieve? Why do you need the AppDelegate? – Adam Aug 09 '18 at 17:07
  • I have a function that I'm using in `AppDelegate.swift` multiple times. I need to call it once from `TodayViewController.swift`. If possible, I don't want to create the function in `TodayViewController.swift` again. –  Aug 09 '18 at 17:10
  • That's not possible... your app and the extension live in a different space... – Adam Aug 09 '18 at 17:23
  • Okay, thanks for the information. –  Aug 09 '18 at 17:28
  • Would be nice if you accepted my answer :) – Adam Aug 09 '18 at 17:40
  • 1
    Can you please mention the "information" in your answer? –  Aug 09 '18 at 17:42