Class
UIApplication
The centralized point of control and coordination for apps running in iOS.
--iOS中运行的app的集中控制和协调点
Declaration
class UIApplication : UIResponder
Overview --概览
Every iOS app has exactly one instance of UIApplication
(or, very rarely, a subclass of UIApplication
). When an app is launched, the system calls the UIApplicationMain(_:_:_:_:)
function; among its other tasks, this function creates a Singleton UIApplication
object. Thereafter you access the object by calling the shared
class method.
--每个iOS应用程序都只有一个UIApplication实例(或者,很少有,UIApplication的子类)。★ 当app启动时,系统就会自动调用UIApplicationMain(_:_:_:_:)
方法 (现在一般用注解@UIApplicationMain)★ ; 在这个方法的众多任务中,其中一个任务会创建一个单例的UIApplication对象。然后,你可以通过调用静态方法shared
来访问该单例对象。
A major role of your app’s application object is to handle the initial routing of incoming user events. It dispatches action messages forwarded to it by control objects (instances of the UIControl
class) to appropriate target objects. The application object maintains a list of open windows (UIWindow
objects) and through those can retrieve any of the app’s UIView
objects.
--app’s application对象的一个主要作用就是处理“传入的用户事件”的初始路由。UIApplication实例将由“控制对象”(UIControl类的实例)转发给它的”动作消息“ 分派给 适当的目标对象。UIApplication实例维护一个“打开的窗口”(UIWindow对象)的列表,通过这些对象可以检索(获取)所有的app的UIView对象。
The UIApplication
class defines a delegate that conforms to the UIApplicationDelegate
protocol and must implement some of the protocol’s methods. The application object informs the delegate of significant runtime events—for example, app launch, low-memory warnings, and app termination—giving it an opportunity to respond appropriately.
--UIApplication类定义了遵循UIApplication delegate协议的★委托对象,并且该委托对象必须实现委托协议的某些方法。UIApplication实例会通知该委托重要的运行时事件,例如,应用程序启动、内存不足警告和应用程序终止,使其有机会作出适当的响应
Apps can cooperatively handle a resource, such as an email or an image file, through the openURL(_:)
method. For example, an app that calls this method with an email URL causes the Mail app to launch and display the message.
--app可以通过openURL(_:)
方法协同地处理资源,如电子邮件或图像文件。例如,某个app使用电子邮件URL调用此方法,将导致邮件app启动并显示消息。
The APIs in this class allow you to manage device-specific behavior. Use your UIApplication
object to do the following:
--此类中的api允许您管理特定于设备的行为。你可以使用UIApplication对象来执行以下操作:
-
Temporarily suspend incoming touch events (
beginIgnoringInteractionEvents()
)
-- 临时挂起传入的触摸事件 -
Register for remote notifications (
registerForRemoteNotifications()
)
--注册远程通知 -
Trigger the undo-redo UI (
applicationSupportsShakeToEdit
)
--触发“撤消-重做”界面 -
Determine whether there is an installed app registered to handle a URL scheme (
canOpenURL(_:)
)
--确定是否有已安装的已注册的用于处理URL方案的app -
Extend the execution of the app so that it can finish a task in the background (
beginBackgroundTask(expirationHandler:)
,beginBackgroundTask(withName:expirationHandler:)
)
--延长应用程序的执行时间,使其可以在后台完成任务 -
Schedule and cancel local notifications (
scheduleLocalNotification(_:)
,cancelLocalNotification(_:)
)
--安排和取消本地通知 -
Coordinate the reception of remote-control events (
beginReceivingRemoteControlEvents()
,endReceivingRemoteControlEvents()
)
--协调远程控制事件的接收 -
Perform app-level state restoration tasks (methods in the Managing the State Restoration Behavior task group)
--执行应用程序级的状态恢复任务
Subclassing Notes --子类化的注意事项
Most apps do not need to subclass UIApplication
. Instead, use an app delegate to manage interactions between the system and the app.
--大多数app都不需要子类化UIApplication。而是,使用一个app委托来管理系统和app之间的交互。
If your app must handle incoming events before the system does—a very rare situation—you can implement a custom event or action dispatching mechanism. To do this, subclass UIApplication
and override the sendEvent(_:)
and/or the sendAction(_:to:from:for:)
methods. For every event you intercept, dispatch it back to the system by calling [super sendEvent:event]
after you handle the event. Intercepting events is only rarely required and you should avoid it if possible.
--如果您的app必须在系统处理之前处理传入的事件(这是一种非常罕见的情况),那么您可以实现自定义事件或动作调度机制。要实现这一点,就可以子类化UIApplication并重写sendEvent(:)和/或 sendAction(:To:from:for:)方法。对于您拦截的每个事件,在处理事件后通过调用[super sendEvent:event]将其发回系统。截取事件很少会用到,您应该尽可能避免使用它。
Topics --专题
Getting the App Instance --获取app的实例
class var shared: UIApplication
--静态属性:单例
Returns the singleton app instance.
Managing the App's Behavior --管理app的行为
var delegate: UIApplicationDelegate?
The delegate of the app object.
protocol UIApplicationDelegate
A set of methods that you use to manage shared behaviors for your app.
Registering for Remote Notifications --注册远程通知
func registerForRemoteNotifications()
Register to receive remote notifications via Apple Push Notification service.
func unregisterForRemoteNotifications()
Unregister for all remote notifications received via Apple Push Notification service.
var isRegisteredForRemoteNotifications: Bool
A Boolean indicating whether the app is currently registered for remote notifications.
Getting the Application State --获取app的状态
var applicationState: UIApplication.State
The runtime state of the app.
The running states of an app
Getting Scene Information --获取scene的信息
var supportsMultipleScenes: Bool
A Boolean value indicating whether the app may display multiple scenes simultaneously.
var connectedScenes: Set<UIScene>
The app's currently connected scenes.
var openSessions: Set<UISceneSession>
The sessions whose scenes are either currently active or archived by the system.
Creating, Destroying, and Updating Scenes --增删改scene
Asks the system to activate an existing scene, or create a new scene and associate it with your app.
Asks the system to dismiss an existing scene and remove it from the app switcher.
func requestSceneSessionRefresh(UISceneSession)
Asks the system to update any system UI associated with the specified scene.
Managing Background Execution --管理后台运行
var backgroundRefreshStatus: UIBackgroundRefreshStatus
Indicates whether the app can refresh content when running in the background.
enum UIBackgroundRefreshStatus
Constants indicating whether background execution is enabled for the app.
class let backgroundRefreshStatusDidChangeNotification: NSNotification.Name
Posted when the app’s status for downloading content in the background changes.
Mark the start of a task that should continue if the app enters the background.
func beginBackgroundTask(expirationHandler: (() -> Void)?) -> UIBackgroundTaskIdentifier
Mark the start of a task that should continue if the app enters the background.
func endBackgroundTask(UIBackgroundTaskIdentifier)
Marks the end of a specific long-running background task.
struct UIBackgroundTaskIdentifier
A unique token that identifies a request to run in the background.
var backgroundTimeRemaining: TimeInterval
The maximum amount of time remaining for the app to run in the background.
Fetching Content in the Background --抓取后台内容
class let backgroundFetchIntervalMinimum: TimeInterval
The smallest fetch interval supported by the system.
class let backgroundFetchIntervalNever: TimeInterval
A fetch interval large enough to prevent fetch operations from occurring.
Opening a URL Resource --打开URL资源
Attempts to open the resource at the specified URL asynchronously.
Returns a Boolean value indicating whether an app is available to handle a URL scheme.
struct UIApplication.OpenExternalURLOptionsKey
Options for opening a URL.
class let openSettingsURLString: String
Used to create a URL that you can pass to the openURL(_:)
method. When you open the URL built from this string, the system launches the Settings app and displays the app’s custom settings, if it has any.
Managing the App Idle Timer --管理app空闲计时器
A Boolean value that controls whether the idle timer is disabled for the app.
Managing the State Restoration Behavior --管理状态复原行为
Tells the app that your code is restoring state asynchronously.
func completeStateRestoration()
Tells the app that your code has finished any asynchronous state restoration.
func ignoreSnapshotOnNextApplicationLaunch()
Prevents the app from using the recent snapshot image during the next launch cycle.
class func registerObject(forStateRestoration: UIStateRestoring, restorationIdentifier: String)
Registers a custom object for use with the state restoration system.
Managing Home Screen Quick Actions for 3D Touch --管理主屏幕的3D触摸快速行动
var shortcutItems: [UIApplicationShortcutItem]?
The Home screen dynamic quick actions for your app; available on devices that support 3D Touch.
Determining the Availability of Protected Content --确定受保护内容的可用性
var isProtectedDataAvailable: Bool
A Boolean value indicating whether content protection is active.
class let protectedDataDidBecomeAvailableNotification: NSNotification.Name
Posted when the protected files become available for your code to access.
class let protectedDataWillBecomeUnavailableNotification: NSNotification.Name
Posted shortly before protected files are locked down and become inaccessible.
Registering for Remote Control Events --注册远程控制事件
func beginReceivingRemoteControlEvents()
Tells the app to begin receiving remote-control events.
func endReceivingRemoteControlEvents()
Tells the app to stop receiving remote-control events.
Controlling App Appearance --控制app的外观
var userInterfaceLayoutDirection: UIUserInterfaceLayoutDirection
Returns the layout direction of the user interface.
enum UIUserInterfaceLayoutDirection
Specifies the directional flow of the user interface.
Controlling and Handling Events --控制和处理事件
Dispatches an event to the appropriate responder objects in the app.
func sendAction(Selector, to: Any?, from: Any?, for: UIEvent?) -> Bool
Sends an action message identified by selector to a specified target.
func beginIgnoringInteractionEvents()
Tells the receiver to suspend the handling of touch-related events.
Deprecatedfunc endIgnoringInteractionEvents()
Tells the receiver to resume the handling of touch-related events.
Deprecatedvar isIgnoringInteractionEvents: Bool
A Boolean value that indicates whether the receiver is ignoring events initiated by touches on the screen.
Deprecatedvar applicationSupportsShakeToEdit: Bool
A Boolean value that determines whether shaking the device displays the undo-redo user interface.
Managing the App's Icon --管理app的图标
var applicationIconBadgeNumber: Int
The number currently set as the badge of the app icon in Springboard.
var supportsAlternateIcons: Bool
A Boolean value indicating whether the app is allowed to change its icon.
var alternateIconName: String?
The name of the icon being displayed for the app.
func setAlternateIconName(String?, completionHandler: ((Error?) -> Void)?)
Changes the app's icon.
Getting App Windows --获取app的window
The app's key window.
Deprecatedvar windows: [UIWindow]
The app's visible and hidden windows.
Getting the Font Sizing Preference --获取字体大小的首选项
var preferredContentSizeCategory: UIContentSizeCategory
The font sizing option preferred by the user.
Constants indicating the preferred size of your content.
static let newValueUserInfoKey: String
A key whose value is an NSString
object reflecting the new value of the preferredContentSizeCategory
property.
static let didChangeNotification: NSNotification.Name
Posted when the user changes the preferred content size setting.
Managing the Default Interface Orientations --管理默认界面方位
func supportedInterfaceOrientations(for: UIWindow?) -> UIInterfaceOrientationMask
Returns the default set of interface orientations to use for the view controllers in the specified window.
Responding to Status Bar Changes --响应状态的变化
The style of the device’s status bar.
The animation applied to the status bar as it is hidden or made visible.
Tracking Controls in the Run Loop --在运行循环中跟踪控件
static let tracking: RunLoop.Mode
The mode set while tracking in controls takes place.
Detecting an App Snapshot --检测app快照
class let userDidTakeScreenshotNotification: NSNotification.Name
Posted when the user presses the Home and Lock buttons to take a screenshot.
Deprecated Symbols --被丢弃的特性
func setMinimumBackgroundFetchInterval(TimeInterval)
Specifies the minimum amount of time that must elapse between background fetch operations.
Deprecatedvar statusBarOrientationAnimationDuration: TimeInterval
The animation duration in seconds for the status bar during a 90 degree orientation change.
Deprecatedclass let didChangeStatusBarFrameNotification: NSNotification.Name
Posted when the frame of the status bar changes.
Deprecatedclass let didChangeStatusBarOrientationNotification: NSNotification.Name
Posted when the orientation of the app’s user interface changes.
Deprecatedclass let willChangeStatusBarOrientationNotification: NSNotification.Name
Posted when the app is about to change the orientation of its interface.
Deprecatedclass let willChangeStatusBarFrameNotification: NSNotification.Name
Posted when the app is about to change the frame of the status bar.
Deprecatedclass let statusBarOrientationUserInfoKey: String
A key whose value is an NSNumber
object that encapsulates a UIInterfaceOrientation
value indicating the current orientation (see UIInterfaceOrientation
). This key is used with didChangeStatusBarOrientationNotification
and willChangeStatusBarOrientationNotification
notifications.
Deprecatedclass let statusBarFrameUserInfoKey: String
A key whose value is an NSValue
object that encapsulates a CGRect
structure expressing the location and size of the new status bar frame. This key is used with didChangeStatusBarFrameNotification
and willChangeStatusBarFrameNotification
notifications.
Deprecatedvar statusBarFrame: CGRect
The frame rectangle defining the area of the status bar.
Deprecatedvar isNetworkActivityIndicatorVisible: Bool
A Boolean value that turns an indicator of network activity on or off.
Deprecatedlet UIMinimumKeepAliveTimeout: TimeInterval
The minimum amount of time (measured in seconds) an app may run a critical background task in the background.
Deprecatedfunc registerUserNotificationSettings(UIUserNotificationSettings)
Registers your preferred options for notifying the user.
Deprecatedvar currentUserNotificationSettings: UIUserNotificationSettings?
Returns the user notification settings for the app.
Deprecatedstruct UIRemoteNotificationType
Constants indicating the types of notifications the app may display to the user.
Deprecatedfunc openURL(URL) -> Bool
Attempts to open the resource at the specified URL.
Deprecatedfunc scheduleLocalNotification(UILocalNotification)
Schedules a local notification for delivery at its encapsulated date and time.
Deprecatedfunc presentLocalNotificationNow(UILocalNotification)
Presents a local notification immediately.
Deprecatedfunc cancelLocalNotification(UILocalNotification)
Cancels the delivery of the specified scheduled local notification.
Deprecatedfunc cancelAllLocalNotifications()
Cancels the delivery of all scheduled local notifications.
Deprecatedvar scheduledLocalNotifications: [UILocalNotification]?
All currently scheduled local notifications.
Deprecatedfunc setNewsstandIconImage(UIImage?)
Sets the icon of a Newsstand app to an image depicting the current issue of a publication.
Deprecatedfunc setKeepAliveTimeout(TimeInterval, handler: (() -> Void)?) -> Bool
Configures a periodic handler for VoIP apps in older versions of iOS.
Deprecatedfunc clearKeepAliveTimeout()
Removes a previously installed periodic handler block.
Deprecatedfunc setStatusBarHidden(Bool, with: UIStatusBarAnimation)
Hides or shows the status bar, optionally animating the transition.
Deprecatedvar isStatusBarHidden: Bool
A Boolean value that determines whether the status bar is hidden.
Deprecatedfunc setStatusBarStyle(UIStatusBarStyle, animated: Bool)
Sets the style of the status bar, optionally animating the transition to the new style.
Deprecatedvar statusBarStyle: UIStatusBarStyle
The current style of the status bar.
Deprecatedfunc setStatusBarOrientation(UIInterfaceOrientation, animated: Bool)
Sets the app's status bar to the specified orientation, optionally animating the transition.
Deprecatedvar statusBarOrientation: UIInterfaceOrientation
The current orientation of the app's status bar.
Deprecatedfunc registerForRemoteNotifications(matching: UIRemoteNotificationType)
Register to receive remote notifications of the specified types via Apple Push Notification service.
Deprecatedfunc enabledRemoteNotificationTypes() -> UIRemoteNotificationType
Returns the types of notifications the app accepts.
Deprecated
Relationships
Inherits From
Conforms To
See Also
Life Cycle
Managing Your App's Life Cycle
Respond to system notifications when your app is in the foreground or background, and handle other significant system-related events.
Responding to the Launch of Your App
Initialize your app’s data structures, prepare your app to run, and respond to any launch-time requests from the system.
protocol UIApplicationDelegate
A set of methods that you use to manage shared behaviors for your app.
Manage multiple instances of your app’s UI simultaneously, and direct resources to the appropriate instance of your UI.