Skip to content

Commit

Permalink
Add background fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
robbiet480 committed Apr 19, 2017
1 parent 31885ac commit cbc6416
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 19 deletions.
36 changes: 32 additions & 4 deletions HomeAssistant/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
print("Realm file path", Realm.Configuration.defaultConfiguration.fileURL!.path)
Fabric.with([Crashlytics.self])

UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)

NetworkActivityIndicatorManager.shared.isEnabled = true

if #available(iOS 10, *) {
Expand Down Expand Up @@ -123,18 +125,44 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
print("Received remote request to provide a location update")
HomeAssistantAPI.sharedInstance.sendOneshotLocation().then { success -> Void in
print("Did successfully send location when requested via APNS?", success)
completionHandler(UIBackgroundFetchResult.noData)
}.catch {error in
print("Error when attempting to submit location update")
Crashlytics.sharedInstance().recordError(error)
if success == true {
completionHandler(UIBackgroundFetchResult.newData)
} else {
completionHandler(UIBackgroundFetchResult.failed)
}
}.catch {error in
print("Error when attempting to submit location update")
Crashlytics.sharedInstance().recordError(error)
completionHandler(UIBackgroundFetchResult.failed)
}
default:
print("Received unknown command via APNS!", userInfo)
completionHandler(UIBackgroundFetchResult.noData)
}
} else {
completionHandler(UIBackgroundFetchResult.failed)
}
} else {
completionHandler(UIBackgroundFetchResult.failed)
}
} else {
completionHandler(UIBackgroundFetchResult.failed)
}
}

func application(_ application: UIApplication,
performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("Background fetch activated!")
HomeAssistantAPI.sharedInstance.sendOneshotLocation().then { success -> Void in
if success == true {
completionHandler(UIBackgroundFetchResult.newData)
} else {
completionHandler(UIBackgroundFetchResult.failed)
}
}.catch {error in
print("Error when attempting to submit location update")
Crashlytics.sharedInstance().recordError(error)
completionHandler(UIBackgroundFetchResult.failed)
}
}

Expand Down
34 changes: 19 additions & 15 deletions HomeAssistant/HAAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -217,14 +217,15 @@ public class HomeAssistantAPI {
"dev_id": deviceID
]

_ = self.identifyDevice()

self.CallService(domain: "device_tracker",
service: "see",
serviceData: locationUpdate as [String : Any]).then {_ in
print("Device seen!")
}.catch {err in
Crashlytics.sharedInstance().recordError(err as NSError)
firstly {
self.identifyDevice()
}.then {_ in
self.CallService(domain: "device_tracker", service: "see", serviceData: locationUpdate)
}.then { _ in
print("Device seen!")
}.catch { err in
print("Error when updating location!", err)
Crashlytics.sharedInstance().recordError(err as NSError)
}

UIDevice.current.isBatteryMonitoringEnabled = false
Expand All @@ -244,7 +245,7 @@ public class HomeAssistantAPI {
notificationIdentifer = "\(zone!.Name)_exited"
shouldNotify = prefs.bool(forKey: "exitNotifications")
case .SignificantLocationUpdate:
notificationBody = "Significant location change detected, notifying Home Assistant"
notificationBody = "Significant location change detected"
notificationIdentifer = "sig_change"
shouldNotify = prefs.bool(forKey: "significantLocationChangeNotifications")
default:
Expand Down Expand Up @@ -350,18 +351,21 @@ public class HomeAssistantAPI {

func sendOneshotLocation() -> Promise<Bool> {
return Promise { fulfill, reject in
Location.getLocation(accuracy: .neighborhood, frequency: .oneShot, success: { (_, location) in
Location.getLocation(accuracy: .neighborhood, frequency: .oneShot, timeout: 25, success: { (_, location) in
print("A new update of location is available: \(location)")
self.submitLocation(updateType: .Manual,
coordinates: location.coordinate,
accuracy: location.horizontalAccuracy,
zone: nil)
fulfill(true)
}) { (request, _, error) in
request.cancel() // stop continous location monitoring on error
print("Error when trying to get a oneshot location!", error)
Crashlytics.sharedInstance().recordError(error)
reject(error)
}) { (_, _, error) in
if error == LocationError.timeout {
fulfill(false)
} else {
print("Error when trying to get a oneshot location!", error)
Crashlytics.sharedInstance().recordError(error)
reject(error)
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions HomeAssistant/Resources/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
<string>To allow PromiseKit to work under iOS 10</string>
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>location</string>
<string>remote-notification</string>
</array>
Expand Down

0 comments on commit cbc6416

Please sign in to comment.