In Objective C it was simple: it was sufficient to update the main.m file and change the UIApplicationMain() parameters
return UIApplicationMain(argc, argv, NSStringFromClass([CustomUIApplication class]), NSStringFromClass([AppDelegate class]));
But in swift there is no main.m file, since the guide says
“Code written at global scope is used as the entry point for the program, so you don’t need a main function.”
So, how to subclass UIApplication in swift?? Any suggestion?
Ok, I've found the solution
First, I've noticed that, at the top of the AppDelegate.swift file, there is this line
Since this line is outside any scope (it's at file level), it's executed immediately, and I assume that the compiler translate it in a standard main function.
So, I did this, starting from a new Swift-Only application:
@UIApplicationMain
IMPORTANT the file MUST BE NAMED main.swift, since top level statements are not supported on other files! You can't add the UIApplicationMain() call inside any other file, otherwise you'll receive this error:
This is the main.swift file
Then, create a swift file for the UIApplication subclass, FLApplication.swift, with this code:
now, UIApplication is correctly subclassed and you'll see the "send event" messages in the log
EDIT - MARCH 2015
As commented by Hu Junfeng now the explanations about
UIApplicationMain
and the main.swift file are documented in the Attributes section of The Swift Language Reference: LinkAs commented by Thomas Verbeek In the XCode 6.3 Beta, you might find that C_ARGC and C_ARGV have been renamed to Process.argc and Process.unsafeArgv respectively. Your UIApplicationMain call in the main.swift file will need updating to:
The pre-XCode 8 syntax was
EDIT - DEC 2016
Solution for Xcode 8, before beta 6
One alternative is to extend
UIApplication
instead of subclassing it. According to the iBook released by Apple, extensions in Swift can:If your needs in subclassing
UIApplication
are satisfied by those capabilities, an Extension might be the way to go.