-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackgroundObserver.swift
More file actions
82 lines (64 loc) · 2.77 KB
/
BackgroundObserver.swift
File metadata and controls
82 lines (64 loc) · 2.77 KB
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
80
81
82
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Contains the code related to automatic background tasks
*/
import UIKit
/**
`BackgroundObserver` is an `OperationObserver` that will automatically begin
and end a background task if the application transitions to the background.
This would be useful if you had a vital `Operation` whose execution *must* complete,
regardless of the activation state of the app. Some kinds network connections
may fall in to this category, for example.
*/
class BackgroundObserver: NSObject, OperationObserver {
// MARK: Properties
private var identifier = UIBackgroundTaskInvalid
private var isInBackground = false
override init() {
super.init()
// We need to know when the application moves to/from the background.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BackgroundObserver.didEnterBackground(_:)), name: UIApplicationDidEnterBackgroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BackgroundObserver.didEnterForeground(_:)), name: UIApplicationDidBecomeActiveNotification, object: nil)
isInBackground = UIApplication.sharedApplication().applicationState == .Background
// If we're in the background already, immediately begin the background task.
if isInBackground {
startBackgroundTask()
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
@objc func didEnterBackground(notification: NSNotification) {
if !isInBackground {
isInBackground = true
startBackgroundTask()
}
}
@objc func didEnterForeground(notification: NSNotification) {
if isInBackground {
isInBackground = false
endBackgroundTask()
}
}
private func startBackgroundTask() {
if identifier == UIBackgroundTaskInvalid {
identifier = UIApplication.sharedApplication().beginBackgroundTaskWithName("BackgroundObserver", expirationHandler: {
self.endBackgroundTask()
})
}
}
private func endBackgroundTask() {
if identifier != UIBackgroundTaskInvalid {
UIApplication.sharedApplication().endBackgroundTask(identifier)
identifier = UIBackgroundTaskInvalid
}
}
// MARK: Operation Observer
func operationDidStart(operation: Operation) { }
func operation(operation: Operation, didProduceOperation newOperation: NSOperation) { }
func operationDidFinish(operation: Operation, errors: [NSError]) {
endBackgroundTask()
}
}