Skip to content

Commit

Permalink
SwiftLint part deux
Browse files Browse the repository at this point in the history
  • Loading branch information
robbiet480 committed Jan 7, 2017
1 parent 30699ed commit 2a52185
Show file tree
Hide file tree
Showing 26 changed files with 1,252 additions and 774 deletions.
2 changes: 2 additions & 0 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
disabled_rules:
- variable_name
excluded:
- fastlane
- HomeAssistantTests
Expand Down
24 changes: 18 additions & 6 deletions APNSAttachmentService/NotificationService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ final class NotificationService: UNNotificationServiceExtension {
private var baseURL: String = ""
private var apiPassword: String = ""

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable function_body_length
override func didReceive(_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
print("APNSAttachmentService started!")
print("Received userInfo", request.content.userInfo)
self.contentHandler = contentHandler
Expand Down Expand Up @@ -101,16 +104,23 @@ final class NotificationService: UNNotificationServiceExtension {
attachmentOptions[UNNotificationAttachmentOptionsThumbnailHiddenKey] = attachmentHideThumbnail
}
guard let attachmentData = NSData(contentsOf:attachmentURL) else { return failEarly() }
guard let attachment = UNNotificationAttachment.create(fileIdentifier: attachmentURL.lastPathComponent, data: attachmentData, options: attachmentOptions) else { return failEarly() }
guard let attachment = UNNotificationAttachment.create(fileIdentifier: attachmentURL.lastPathComponent,
data: attachmentData,
options: attachmentOptions) else {
return failEarly()
}

content.attachments.append(attachment)

contentHandler(content.copy() as! UNNotificationContent)
if let copiedContent = content.copy() as? UNNotificationContent {
contentHandler(copiedContent)
}
}

override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
// Use this as an opportunity to deliver your "best attempt" at modified content,
// otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
Expand All @@ -121,10 +131,12 @@ final class NotificationService: UNNotificationServiceExtension {
extension UNNotificationAttachment {

/// Save the attachment URL to disk
static func create(fileIdentifier: String, data: NSData, options: [AnyHashable : Any]?) -> UNNotificationAttachment? {
static func create(fileIdentifier: String, data: NSData,
options: [AnyHashable : Any]?) -> UNNotificationAttachment? {
let fileManager = FileManager.default
let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
let tmpSubFolderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true)
let tmpSubFolderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName,
isDirectory: true)

do {
try fileManager.createDirectory(at: tmpSubFolderURL!, withIntermediateDirectories: true, attributes: nil)
Expand Down
141 changes: 76 additions & 65 deletions HomeAssistant/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,9 @@ import RealmSwift
import UserNotifications
import AlamofireNetworkActivityIndicator

let realmConfig = Realm.Configuration(
schemaVersion: 2,

migrationBlock: { _, oldSchemaVersion in
if (oldSchemaVersion < 1) {
}
})
let realmConfig = Realm.Configuration(schemaVersion: 2, migrationBlock: nil)

// swiftlint:disable:next force_try
let realm = try! Realm(configuration: realmConfig)

@UIApplicationMain
Expand All @@ -31,7 +26,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

let prefs = UserDefaults(suiteName: "group.io.robbie.homeassistant")!

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
// swiftlint:disable:next line_length
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil) -> Bool {
migrateUserDefaultsToAppGroups()
Realm.Configuration.defaultConfiguration = realmConfig
print("Realm file path", Realm.Configuration.defaultConfiguration.fileURL!.path)
Expand All @@ -43,9 +40,13 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
UNUserNotificationCenter.current().delegate = self
}

Crashlytics.sharedInstance().setObjectValue(prefs.integer(forKey: "lastInstalledVersion"), forKey: "lastInstalledVersion")
let buildNumber = Int(string: Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")! as! String)
prefs.set(buildNumber, forKey: "lastInstalledVersion")
Crashlytics.sharedInstance().setObjectValue(prefs.integer(forKey: "lastInstalledVersion"),
forKey: "lastInstalledVersion")
if let bundleVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") {
if let stringedBundleVersion = bundleVersion as? String {
prefs.set(stringedBundleVersion, forKey: "lastInstalledVersion")
}
}

initAPI()

Expand All @@ -71,47 +72,35 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
return
}.catch {err -> Void in
print("ERROR", err)
// let settingsView = SettingsViewController()
// settingsView.title = "Settings"
// settingsView.showErrorConnectingMessage = true
// let navController = UINavigationController(rootViewController: settingsView)
// self.window?.makeKeyAndVisible()
// self.window?.rootViewController!.present(navController, animated: true, completion: nil)
let settingsView = SettingsViewController()
settingsView.title = "Settings"
settingsView.showErrorConnectingMessage = true
let navController = UINavigationController(rootViewController: settingsView)
self.window?.makeKeyAndVisible()
self.window?.rootViewController!.present(navController, animated: true, completion: nil)
}
}
}

func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationWillResignActive(_ application: UIApplication) {}

func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationDidEnterBackground(_ application: UIApplication) {}

func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationWillEnterForeground(_ application: UIApplication) {}

func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationDidBecomeActive(_ application: UIApplication) {}

func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func applicationWillTerminate(_ application: UIApplication) {}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

self.prefs.setValue(deviceTokenString, forKey: "deviceToken")
self.prefs.setValue(tokenString, forKey: "deviceToken")

print("Registering push with deviceTokenString: \(deviceTokenString)")
print("Registering push with tokenString: \(tokenString)")

_ = HomeAssistantAPI.sharedInstance.registerDeviceForPush(deviceToken: deviceTokenString).then { pushId -> Void in
_ = HomeAssistantAPI.sharedInstance.registerDeviceForPush(deviceToken: tokenString).then { pushId -> Void in
print("Registered for push. PushID:", pushId)
CLSLogv("Registered for push:", getVaList([pushId]))
Crashlytics.sharedInstance().setUserIdentifier(pushId)
Expand All @@ -120,54 +109,69 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Swift.Error) {
func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Swift.Error) {
print("Error when trying to register for push", error)
Crashlytics.sharedInstance().recordError(error)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("Received remote notification in completion handler!")

let userInfoDict = userInfo as! [String:Any]

if let hadict = userInfoDict["homeassistant"] as? [String:String] {
if let command = hadict["command"] {
switch command {
case "request_location_update":
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)
if let userInfoDict = userInfo as? [String:Any] {
if let hadict = userInfoDict["homeassistant"] as? [String:String] {
if let command = hadict["command"] {
switch command {
case "request_location_update":
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)
completionHandler(UIBackgroundFetchResult.failed)
}
default:
print("Received unknown command via APNS!", userInfo)
completionHandler(UIBackgroundFetchResult.noData)
}.catch {error in
print("Error when attempting to submit location update")
Crashlytics.sharedInstance().recordError((error as Any) as! NSError)
completionHandler(UIBackgroundFetchResult.failed)
}
default:
print("Received unknown command via APNS!", userInfo)
completionHandler(UIBackgroundFetchResult.noData)
}
}
}
}

func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable : Any], withResponseInfo responseInfo: [AnyHashable : Any], completionHandler: @escaping () -> Void) {
func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?,
forRemoteNotification userInfo: [AnyHashable : Any],
withResponseInfo responseInfo: [AnyHashable : Any],
completionHandler: @escaping () -> Void) {
var userInput: String? = nil
if let userText = responseInfo[UIUserNotificationActionResponseTypedTextKey] as? String {
userInput = userText
}
let _ = HomeAssistantAPI.sharedInstance.handlePushAction(identifier: identifier!, userInfo: userInfo, userInput: userInput)
let _ = HomeAssistantAPI.sharedInstance.handlePushAction(identifier: identifier!,
userInfo: userInfo,
userInput: userInput)
}

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
func application(_ app: UIApplication,
open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
var serviceData: [String:String] = url.queryItems!
serviceData["sourceApplication"] = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String
switch url.host! {
case "call_service": // homeassistant://call_service/device_tracker.see?entity_id=device_tracker.entity
let _ = HomeAssistantAPI.sharedInstance.CallService(domain: url.pathComponents[1].components(separatedBy: ".")[0], service: url.pathComponents[1].components(separatedBy: ".")[1], serviceData: serviceData)
let domain = url.pathComponents[1].components(separatedBy: ".")[0]
let service = url.pathComponents[1].components(separatedBy: ".")[1]
let _ = HomeAssistantAPI.sharedInstance.CallService(domain: domain,
service: service,
serviceData: serviceData)
break
case "fire_event": // homeassistant://fire_event/custom_event?entity_id=device_tracker.entity
let _ = HomeAssistantAPI.sharedInstance.CreateEvent(eventType: url.pathComponents[1], eventData: serviceData)
let _ = HomeAssistantAPI.sharedInstance.CreateEvent(eventType: url.pathComponents[1],
eventData: serviceData)
break
case "send_location": // homeassistant://send_location/
let _ = HomeAssistantAPI.sharedInstance.sendOneshotLocation()
Expand All @@ -181,21 +185,28 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

@available(iOS 10, *)
extension AppDelegate: UNUserNotificationCenterDelegate {
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
public func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
var userText: String? = nil
if let textInput = response as? UNTextInputNotificationResponse {
userText = textInput.userText
}
HomeAssistantAPI.sharedInstance.handlePushAction(identifier: response.actionIdentifier, userInfo: response.notification.request.content.userInfo, userInput: userText).then { _ in
completionHandler()
HomeAssistantAPI.sharedInstance.handlePushAction(identifier: response.actionIdentifier,
userInfo: response.notification.request.content.userInfo,
userInput: userText).then { _ in
completionHandler()
}.catch { err -> Void in
print("Error: \(err)")
Crashlytics.sharedInstance().recordError(err)
completionHandler()
}
}

public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
public func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
// swiftlint:disable:next line_length
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
}
3 changes: 2 additions & 1 deletion HomeAssistant/Classes/Components/BinarySensorComponent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,14 @@ class BinarySensor: SwitchableEntity {
return "mdi:radiobox-blank"
}

// swiftlint:disable:next cyclomatic_complexity
override func StateIcon() -> String {
if self.MobileIcon != nil { return self.MobileIcon! }
if self.Icon != nil { return self.Icon! }

let activated = (self.IsOn == false)
if let sensorClass = self.SensorClass {
switch (sensorClass) {
switch sensorClass {
case "connectivity":
return activated ? "mdi:server-network-off" : "mdi:server-network"
case "light":
Expand Down
Loading

0 comments on commit 2a52185

Please sign in to comment.