Swift Note

兴趣是最好的老师

Swift sharedApplication 详解

感觉 sharedApplication 是一个很厉害的存在,它是 UIApplication 的一个方法:

sharedApplication 返回 UIApplicationMain 方法中创建的实例

用法也很简单:

//属性类
UIApplication.sharedApplication.xxx  
//子方法
UIApplication.sharedApplication.xxx()  

处理和控制 UIEvent

//开始忽略 Event
UIApplication.sharedApplication.beginIgnoringInteractionEvents()  
//结束忽略 Event
UIApplication.sharedApplication.endIgnoringInteractionEvents()  
//是否在忽略 Event
UIApplication.sharedApplication.isIgnoringInteractionEvents  

晃动手机撤销编辑

UIApplication.sharedApplication.applicationSupportsShakeToEdit = true  

设置状态栏

UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true)  

不过 setStatusBarStyle 在 iOS 9 中已经被弃用了,需要使用

UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default  

也可以用 preferredStatusBarStyle 来实现:

override func preferredStatusBarStyle() -> UIStatusBarStyle {  
    return UIStatusBarStyle.Default
}

隐藏状态栏

UIApplication.sharedApplication().statusBarHidden = true  

当然也可以用 prefersStatusBarHidden 来实现:

override func prefersStatusBarHidden() -> Bool {  
    return true
}

openURL

这个也是很强大的:

//打开网址
UIApplication.sharedApplication().openURL(NSURL(string: "https://www.swiftnote.io")!)

//发短信
UIApplication.sharedApplication().openURL(NSURL(string: "tel://10086")!)

//发邮件
UIApplication.sharedApplication().openURL(NSURL(string: "mailto://youemail@youdomain.com")!)

//打电话
UIApplication.sharedApplication().openURL(NSURL(string: "tel://10086")!)

设置 app 图表右上角红点数字

let setting = UIUserNotificationSettings(forTypes: .Badge, categories: .None)  
        UIApplication.sharedApplication().registerUserNotificationSettings(setting)

UIApplication.sharedApplication().applicationIconBadgeNumber = 10  

设置联网指示器

联网指示器就是访问网络时,状态栏的那个小菊花

UIApplication.sharedApplication().networkActivityIndicatorVisible = false  

后台相关

// app 状态
UIApplication.sharedApplication().applicationState  
// 设置后台运行时间
UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(3600)

//        获取 app 后台运行时间
UIApplication.sharedApplication().backgroundTimeRemaining

//        后台刷新状态
UIApplication.sharedApplication().backgroundRefreshStatus

//        后台任务
UIApplication.sharedApplication().beginBackgroundTaskWithName("task", expirationHandler: nil)

UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler(nil)

UIApplication.sharedApplication().endBackgroundTask(1)

//        后台同步控制
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()

UIApplication.sharedApplication().endReceivingRemoteControlEvents()

常用的貌似就这些,有用到再补充

神飞

没有什么能够阻挡,我对自由的向往