标签:
前面讲了如何让程序申请后台短时运行。但这个额外延长的时间毕竟有限。所以从iOS7起又引入两种在后台运行任务的方式:后台获取和后台通知。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
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() } } |
5,后台获取测试
Swift - 后台获取数据(Background Fetch)的实现
标签:
原文地址:http://www.cnblogs.com/Free-Thinker/p/4844889.html