import UIKit
@UIApplicationMain
class AppDelegate : UIResponder , UIApplicationDelegate {
var window: UIWindow ?
func application(application: UIApplication ,
didFinishLaunchingWithOptions launchOptions: [ NSObject : AnyObject ]?) -> Bool {
//开启通知
let settings = UIUserNotificationSettings (forTypes: [. Alert , . Badge , . Sound ],
categories: nil )
application.registerUserNotificationSettings(settings)
return true
}
func applicationWillResignActive(application: UIApplication ) {
}
func applicationDidEnterBackground(application: UIApplication ) {
//虽然定义了后台获取的最短时间,但iOS会自行以它认定的最佳时间来唤醒程序,这个我们无法控制
//UIApplicationBackgroundFetchIntervalMinimum 尽可能频繁的调用我们的Fetch方法
application.setMinimumBackgroundFetchInterval( UIApplicationBackgroundFetchIntervalMinimum )
}
func applicationWillEnterForeground(application: UIApplication ) {
}
func applicationDidBecomeActive(application: UIApplication ) {
}
func applicationWillTerminate(application: UIApplication ) {
}
//后台获取数据
func application(application: UIApplication ,
performFetchWithCompletionHandler completionHandler: ( UIBackgroundFetchResult ) -> Void ) {
//创建NSURL对象
let url: NSURL ! = NSURL (string: "http://api.k780.com:88/?app=life.time&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json" )
//创建请求对象
let request: NSURLRequest = NSURLRequest ( URL : url)
let session = NSURLSession .sharedSession()
let dataTask = session.dataTaskWithRequest(request,
completionHandler: {(data, response, error) -> Void in
if error != nil {
print (error?.code)
print (error?.description)
//让OS知道获取数据失败
completionHandler( UIBackgroundFetchResult . Failed )
} else {
let str = NSString (data: data!, encoding: NSUTF8StringEncoding )
print (str)
//清除所有本地推送
//UIApplication.sharedApplication().cancelAllLocalNotifications()
//创建UILocalNotification来进行本地消息通知
let localNotification = UILocalNotification ()
//推送时间(立刻推送)
localNotification.fireDate = NSDate (timeIntervalSinceNow: 0)
//时区
localNotification.timeZone = NSTimeZone .defaultTimeZone()
//推送内容
localNotification.alertBody = "获取时间成功:\(str)"
//声音
localNotification.soundName = UILocalNotificationDefaultSoundName
UIApplication .sharedApplication().scheduleLocalNotification(localNotification)
//让OS知道已经获取到新数据
completionHandler( UIBackgroundFetchResult . NewData )
//completionHandler(UIBackgroundFetchResult.NoData)
}
}) as NSURLSessionTask
//使用resume方法启动任务
dataTask.resume()
}
}
|