diff --git a/Example/Pods/Pods.xcodeproj/project.pbxproj b/Example/Pods/Pods.xcodeproj/project.pbxproj index 6726d83..f183587 100644 --- a/Example/Pods/Pods.xcodeproj/project.pbxproj +++ b/Example/Pods/Pods.xcodeproj/project.pbxproj @@ -799,6 +799,11 @@ attributes = { LastSwiftUpdateCheck = 0700; LastUpgradeCheck = 0710; + TargetAttributes = { + 9DB05EFC751028DD93CF970F1102971B = { + LastSwiftMigration = 0830; + }; + }; }; buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; compatibilityVersion = "Xcode 3.2"; @@ -1130,6 +1135,7 @@ PRODUCT_NAME = HealthKitSampleGenerator; SDKROOT = iphoneos; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; @@ -1304,6 +1310,7 @@ SDKROOT = iphoneos; SKIP_INSTALL = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = ""; diff --git a/Pod/Classes/ExportConfiguration.swift b/Pod/Classes/ExportConfiguration.swift index 1236f33..e8655d1 100644 --- a/Pod/Classes/ExportConfiguration.swift +++ b/Pod/Classes/ExportConfiguration.swift @@ -35,9 +35,9 @@ internal extension ExportConfiguration { case .ALL: return predicateNoCorreltion case .ADDED_BY_THIS_APP: - return NSCompoundPredicate(andPredicateWithSubpredicates: [predicateNoCorreltion, HKQuery.predicateForObjectsFromSource(HKSource.defaultSource())]) + return NSCompoundPredicate(andPredicateWithSubpredicates: [predicateNoCorreltion, HKQuery.predicateForObjects(from: HKSource.default())]) case .GENERATED_BY_THIS_APP: - return NSCompoundPredicate(andPredicateWithSubpredicates: [predicateNoCorreltion, HKQuery.predicateForObjectsWithMetadataKey("GeneratorSource", allowedValues: ["HSG"])]) + return NSCompoundPredicate(andPredicateWithSubpredicates: [predicateNoCorreltion, HKQuery.predicateForObjects(withMetadataKey: "GeneratorSource", allowedValues: ["HSG"])]) } } diff --git a/Pod/Classes/ExportTargets.swift b/Pod/Classes/ExportTargets.swift index a543e19..238121d 100644 --- a/Pod/Classes/ExportTargets.swift +++ b/Pod/Classes/ExportTargets.swift @@ -19,77 +19,77 @@ public protocol ExportTarget { func endExport() throws -> Void /// output the metadata of the profile - func writeMetaData(creationDate creationDate: NSDate, profileName: String, version: String) throws -> Void + func writeMetaData(creationDate: Date, profileName: String, version: String) throws -> Void /// output the user data from healthkit - func writeUserData(userData: Dictionary ) throws -> Void + func writeUserData(_ userData: Dictionary ) throws -> Void /// start writing a type - func startWriteType(type:HKSampleType) throws -> Void + func startWriteType(_ type:HKSampleType) throws -> Void /// end writing a type func endWriteType() throws -> Void /// write a dictionary to the output - e.g. a dict of the sample data - func writeDictionary(entry:Dictionary ) throws -> Void + func writeDictionary(_ entry:Dictionary ) throws -> Void } /// An export target that generetes a single json doc for the whole data. -public class JsonSingleDocExportTarget { +open class JsonSingleDocExportTarget { - private(set) var jsonWriter: JsonWriter + fileprivate(set) var jsonWriter: JsonWriter init(outputStream: OutputStream){ self.jsonWriter = JsonWriter(outputStream: outputStream) } /// see ExportTarget Protocol - public func startExport() -> Void { + open func startExport() -> Void { jsonWriter.writeStartObject() } /// see ExportTarget Protocol - public func endExport() { + open func endExport() { jsonWriter.writeEndObject() jsonWriter.close() } /// see ExportTarget Protocol - public func writeMetaData(creationDate creationDate: NSDate, profileName: String, version: String) { + open func writeMetaData(creationDate: Date, profileName: String, version: String) { jsonWriter.writeObjectFieldStart(HealthKitConstants.META_DATA) jsonWriter.writeField(HealthKitConstants.CREATION_DATE, value: creationDate) jsonWriter.writeField(HealthKitConstants.PROFILE_NAME, value: profileName) jsonWriter.writeField(HealthKitConstants.VERSION, value: version) - jsonWriter.writeField(HealthKitConstants.TYPE, value: String(JsonSingleDocExportTarget)) + jsonWriter.writeField(HealthKitConstants.TYPE, value: String(describing: JsonSingleDocExportTarget.self)) jsonWriter.writeEndObject() } /// see ExportTarget Protocol - public func writeUserData(userData: Dictionary ) throws { + open func writeUserData(_ userData: Dictionary ) throws { try jsonWriter.writeFieldWithObject(HealthKitConstants.USER_DATA, value: userData) } /// see ExportTarget Protocol - public func startWriteType(type:HKSampleType) -> Void { - jsonWriter.writeArrayFieldStart(String(type)) + open func startWriteType(_ type:HKSampleType) -> Void { + jsonWriter.writeArrayFieldStart(type.identifier) } /// see ExportTarget Protocol - public func endWriteType() -> Void { + open func endWriteType() -> Void { jsonWriter.writeEndArray() } /// see ExportTarget Protocol - public func writeDictionary(entry:Dictionary ) throws -> Void { + open func writeDictionary(_ entry:Dictionary ) throws -> Void { try jsonWriter.writeObject(entry) } } /// an export target that creates a single json doc within a file -public class JsonSingleDocAsFileExportTarget : JsonSingleDocExportTarget, ExportTarget { +open class JsonSingleDocAsFileExportTarget : JsonSingleDocExportTarget, ExportTarget { /// the full path of the ouput file - private(set) public var outputFileName: String - private(set) var overwriteIfExist = false + fileprivate(set) open var outputFileName: String + fileprivate(set) var overwriteIfExist = false /** Instantiate a JsonSingleDocAsFileExportTarget. @@ -107,11 +107,11 @@ public class JsonSingleDocAsFileExportTarget : JsonSingleDocExportTarget, Export Check the validity of the ExportTarget. - Returns: true if the file does not already exist or overwrite is allowed. */ - public func isValid() -> Bool { + open func isValid() -> Bool { var valid = true // if the outputFileName already exists, the state is only valid, if overwrite is allowed - if NSFileManager.defaultManager().fileExistsAtPath(outputFileName) { + if FileManager.default.fileExists(atPath: outputFileName) { valid = valid && overwriteIfExist } @@ -120,7 +120,7 @@ public class JsonSingleDocAsFileExportTarget : JsonSingleDocExportTarget, Export } /// an export target that creates a single json doc in memory -public class JsonSingleDocInMemExportTarget: JsonSingleDocExportTarget, ExportTarget { +open class JsonSingleDocInMemExportTarget: JsonSingleDocExportTarget, ExportTarget { /// create a JsonSingleDocExportTarget in Mem public init(){ @@ -128,12 +128,12 @@ public class JsonSingleDocInMemExportTarget: JsonSingleDocExportTarget, ExportTa } /// is always valid - public func isValid() -> Bool { + open func isValid() -> Bool { return true } /// see ExportTarget Protocol - public func getJsonString() -> String { + open func getJsonString() -> String { return jsonWriter.getJsonString() } -} \ No newline at end of file +} diff --git a/Pod/Classes/HealthKitConstants.swift b/Pod/Classes/HealthKitConstants.swift index 870330c..17291cf 100644 --- a/Pod/Classes/HealthKitConstants.swift +++ b/Pod/Classes/HealthKitConstants.swift @@ -35,138 +35,138 @@ class HealthKitConstants { static let healthKitCharacteristicsTypes: Set = Set(arrayLiteral: - HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)!, - HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex)!, - HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBloodType)!, - HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierFitzpatrickSkinType)! + HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.dateOfBirth)!, + HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.biologicalSex)!, + HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.bloodType)!, + HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.fitzpatrickSkinType)! ) static let healthKitCategoryTypes: Set = Set(arrayLiteral: - HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis)!, - HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierCervicalMucusQuality)!, - HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierOvulationTestResult)!, - HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierMenstrualFlow)!, - HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierIntermenstrualBleeding)!, - HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSexualActivity)! + HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis)!, + HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.cervicalMucusQuality)!, + HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.ovulationTestResult)!, + HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.menstrualFlow)!, + HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.intermenstrualBleeding)!, + HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sexualActivity)! ) // not writable static let healthKitCategoryLockedTypes: Set = Set(arrayLiteral: - HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierAppleStandHour)! + HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.appleStandHour)! ) static let healthKitQuantityTypes: Set = Set(arrayLiteral: // Body Measurements - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyFatPercentage)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierLeanBodyMass)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMassIndex)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyFatPercentage)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.leanBodyMass)!, // Fitness - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceCycling)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBasalEnergyBurned)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierFlightsClimbed)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceCycling)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.basalEnergyBurned)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.flightsClimbed)!, // Vitals - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyTemperature)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBasalBodyTemperature)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodPressureSystolic)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodPressureDiastolic)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierRespiratoryRate)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyTemperature)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.basalBodyTemperature)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodPressureSystolic)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodPressureDiastolic)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.respiratoryRate)!, // Results - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierOxygenSaturation)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierPeripheralPerfusionIndex)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodGlucose)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierNumberOfTimesFallen)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierElectrodermalActivity)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierInhalerUsage)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodAlcoholContent)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierForcedVitalCapacity)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierForcedExpiratoryVolume1)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierPeakExpiratoryFlowRate)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.oxygenSaturation)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.peripheralPerfusionIndex)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.numberOfTimesFallen)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.electrodermalActivity)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.inhalerUsage)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodAlcoholContent)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.forcedVitalCapacity)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.forcedExpiratoryVolume1)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.peakExpiratoryFlowRate)!, // Nutrition - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatTotal)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatPolyunsaturated)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatMonounsaturated)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFatSaturated)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCholesterol)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySodium)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCarbohydrates)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFiber)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySugar)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryEnergyConsumed)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryProtein)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminA)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminB6)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminB12)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminC)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminD)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminE)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminK)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCalcium)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryIron)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryThiamin)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryRiboflavin)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryNiacin)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryFolate)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryBiotin)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryPantothenicAcid)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryPhosphorus)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryIodine)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryMagnesium)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryZinc)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietarySelenium)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCopper)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryManganese)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryChromium)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryMolybdenum)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryChloride)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryPotassium)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryCaffeine)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryWater)!, - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierUVExposure)! + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryFatTotal)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryFatPolyunsaturated)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryFatMonounsaturated)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryFatSaturated)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCholesterol)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietarySodium)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCarbohydrates)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryFiber)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietarySugar)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryEnergyConsumed)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryProtein)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryVitaminA)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryVitaminB6)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryVitaminB12)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryVitaminC)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryVitaminD)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryVitaminE)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryVitaminK)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCalcium)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryIron)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryThiamin)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryRiboflavin)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryNiacin)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryFolate)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryBiotin)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryPantothenicAcid)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryPhosphorus)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryIodine)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryMagnesium)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryZinc)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietarySelenium)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCopper)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryManganese)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryChromium)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryMolybdenum)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryChloride)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryPotassium)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryCaffeine)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.dietaryWater)!, + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.uvExposure)! ) //not writable static let healthKitQuantityLockedTypes: Set = Set(arrayLiteral: - HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierNikeFuel)! + HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.nikeFuel)! ) static let healthKitCorrelationTypes: Set = Set(arrayLiteral: - HKObjectType.correlationTypeForIdentifier(HKCorrelationTypeIdentifierBloodPressure)!, - HKObjectType.correlationTypeForIdentifier(HKCorrelationTypeIdentifierFood)! + HKObjectType.correlationType(forIdentifier: HKCorrelationTypeIdentifier.bloodPressure)!, + HKObjectType.correlationType(forIdentifier: HKCorrelationTypeIdentifier.food)! ) static let workoutType = HKObjectType.workoutType() static func allTypes() -> Set { var allTypes : Set = Set() - allTypes.unionInPlace(healthKitCharacteristicsTypes as Set!) - allTypes.unionInPlace(healthKitQuantityTypes as Set!) - allTypes.unionInPlace(healthKitCategoryTypes as Set!) - allTypes.unionInPlace(healthKitCorrelationTypes as Set!) + allTypes.formUnion(healthKitCharacteristicsTypes as Set!) + allTypes.formUnion(healthKitQuantityTypes as Set!) + allTypes.formUnion(healthKitCategoryTypes as Set!) + allTypes.formUnion(healthKitCorrelationTypes as Set!) allTypes.insert(workoutType) return allTypes } static func authorizationReadTypes() -> Set { var authTypes : Set = Set() - authTypes.unionInPlace(HealthKitConstants.healthKitCharacteristicsTypes as Set!) - authTypes.unionInPlace(HealthKitConstants.healthKitQuantityTypes as Set!) - authTypes.unionInPlace(HealthKitConstants.healthKitQuantityLockedTypes as Set!) - authTypes.unionInPlace(HealthKitConstants.healthKitCategoryTypes as Set!) - authTypes.unionInPlace(HealthKitConstants.healthKitCategoryLockedTypes as Set!) + authTypes.formUnion(HealthKitConstants.healthKitCharacteristicsTypes as Set!) + authTypes.formUnion(HealthKitConstants.healthKitQuantityTypes as Set!) + authTypes.formUnion(HealthKitConstants.healthKitQuantityLockedTypes as Set!) + authTypes.formUnion(HealthKitConstants.healthKitCategoryTypes as Set!) + authTypes.formUnion(HealthKitConstants.healthKitCategoryLockedTypes as Set!) authTypes.insert(HealthKitConstants.workoutType) return authTypes } static func authorizationWriteTypes() -> Set { var authTypes : Set = Set() - authTypes.unionInPlace(HealthKitConstants.healthKitQuantityTypes as Set!) - authTypes.unionInPlace(HealthKitConstants.healthKitCategoryTypes as Set!) + authTypes.formUnion(HealthKitConstants.healthKitQuantityTypes as Set!) + authTypes.formUnion(HealthKitConstants.healthKitCategoryTypes as Set!) authTypes.insert(HealthKitConstants.workoutType) return authTypes } diff --git a/Pod/Classes/HealthKitDataExport.swift b/Pod/Classes/HealthKitDataExport.swift index d26ae54..f6832fc 100644 --- a/Pod/Classes/HealthKitDataExport.swift +++ b/Pod/Classes/HealthKitDataExport.swift @@ -10,13 +10,13 @@ import Foundation import HealthKit /// Export errors -public enum ExportError: ErrorType { +public enum ExportError: Error { /// if health is not available on the device - case HealthDataNotAvailable + case healthDataNotAvailable /// in case of illegal arguments - case IllegalArgumentError(String) + case illegalArgumentError(String) /// in case of error during output - case DataWriteError(String?) + case dataWriteError(String?) } /// what data should be exported @@ -32,11 +32,11 @@ public enum HealthDataToExportType : String { public static let allValues = [ALL, ADDED_BY_THIS_APP, GENERATED_BY_THIS_APP]; } -public typealias ExportCompletion = (ErrorType?) -> Void -public typealias ExportProgress = (message: String, progressInPercent: NSNumber?) -> Void +public typealias ExportCompletion = (Error?) -> Void +public typealias ExportProgress = (_ message: String, _ progressInPercent: NSNumber?) -> Void -class ExportOperation: NSOperation { +class ExportOperation: Operation { var exportConfiguration: ExportConfiguration var exportTargets: [ExportTarget] @@ -50,8 +50,8 @@ class ExportOperation: NSOperation { exportTargets: [ExportTarget], healthStore: HKHealthStore, dataExporter: [DataExporter], - onProgress: ExportProgress, - onError: ExportCompletion, + onProgress: @escaping ExportProgress, + onError: @escaping ExportCompletion, completionBlock: (() -> Void)? ) { @@ -63,7 +63,7 @@ class ExportOperation: NSOperation { self.onError = onError super.init() self.completionBlock = completionBlock - self.qualityOfService = NSQualityOfService.UserInteractive + self.qualityOfService = QualityOfService.userInteractive } override func main() { @@ -75,8 +75,8 @@ class ExportOperation: NSOperation { let exporterCount = Double(dataExporter.count) - for (index, exporter) in dataExporter.enumerate() { - self.onProgress(message: exporter.message, progressInPercent: Double(index)/exporterCount) + for (index, exporter) in dataExporter.enumerated() { + self.onProgress(exporter.message, Double(index)/exporterCount as NSNumber) try exporter.export(healthStore, exportTargets: exportTargets) } @@ -84,7 +84,7 @@ class ExportOperation: NSOperation { try exportTarget.endExport(); } - self.onProgress(message: "export done", progressInPercent: 1.0) + self.onProgress("export done", 1.0) } catch let err { self.onError(err) } @@ -93,10 +93,10 @@ class ExportOperation: NSOperation { } /// exporter for healthkit data -public class HealthKitDataExporter { +open class HealthKitDataExporter { - let exportQueue: NSOperationQueue = { - var queue = NSOperationQueue() + let exportQueue: OperationQueue = { + var queue = OperationQueue() queue.name = "export queue" queue.maxConcurrentOperationCount = 1 return queue @@ -116,26 +116,26 @@ public class HealthKitDataExporter { - Parameter onProgress: callback for progress informations - Parameter onCompletion: callback if the export is done or aborted with an Error. */ - public func export(exportTargets exportTargets: [ExportTarget], exportConfiguration: ExportConfiguration, onProgress: ExportProgress, onCompletion: ExportCompletion) -> Void { + open func export(exportTargets: [ExportTarget], exportConfiguration: ExportConfiguration, onProgress: @escaping ExportProgress, onCompletion: @escaping ExportCompletion) -> Void { if !HKHealthStore.isHealthDataAvailable() { - onCompletion(ExportError.HealthDataNotAvailable) + onCompletion(ExportError.healthDataNotAvailable) return } for exportTarget in exportTargets { if(!exportTarget.isValid()){ - onCompletion(ExportError.IllegalArgumentError("invalid export target \(exportTarget)")) + onCompletion(ExportError.illegalArgumentError("invalid export target \(exportTarget)")) return } } - healthStore.requestAuthorizationToShareTypes(nil, readTypes: HealthKitConstants.authorizationReadTypes()) { + healthStore.requestAuthorization(toShare: nil, read: HealthKitConstants.authorizationReadTypes()) { (success, error) -> Void in /// TODO success error handling - self.healthStore.preferredUnitsForQuantityTypes(HealthKitConstants.healthKitQuantityTypes) { + self.healthStore.preferredUnits(for: HealthKitConstants.healthKitQuantityTypes) { (typeMap, error) in let dataExporter : [DataExporter] = self.getDataExporters(exportConfiguration, typeMap: typeMap) @@ -146,7 +146,7 @@ public class HealthKitDataExporter { healthStore: self.healthStore, dataExporter: dataExporter, onProgress: onProgress, - onError: {(err:ErrorType?) -> Void in + onError: {(err:Error?) -> Void in onCompletion(err) }, completionBlock:{ @@ -160,7 +160,7 @@ public class HealthKitDataExporter { } - internal func getDataExporters(exportConfiguration: ExportConfiguration, typeMap: [HKQuantityType : HKUnit]) -> [DataExporter]{ + internal func getDataExporters(_ exportConfiguration: ExportConfiguration, typeMap: [HKQuantityType : HKUnit]) -> [DataExporter]{ var result : [DataExporter] = [] result.append(MetaDataExporter(exportConfiguration: exportConfiguration)) diff --git a/Pod/Classes/HealthKitDataExporters.swift b/Pod/Classes/HealthKitDataExporters.swift index d12da09..6ea2b4a 100644 --- a/Pod/Classes/HealthKitDataExporters.swift +++ b/Pod/Classes/HealthKitDataExporters.swift @@ -11,13 +11,13 @@ import HealthKit /// Protocol that every data export must conform to. internal protocol DataExporter { var message: String {get} - func export(healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws -> Void + func export(_ healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws -> Void } /// convenience base class for dataexporter internal class BaseDataExporter { var healthQueryError: NSError? = nil - var exportError: ErrorType? = nil + var exportError: Error? = nil var exportConfiguration: ExportConfiguration let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true) @@ -30,7 +30,7 @@ internal class BaseDataExporter { // throw collected errors in the completion block if healthQueryError != nil { print(healthQueryError) - throw ExportError.DataWriteError(healthQueryError?.description) + throw ExportError.dataWriteError(healthQueryError?.description) } if let throwableError = exportError { throw throwableError @@ -43,9 +43,9 @@ internal class MetaDataExporter : BaseDataExporter, DataExporter { internal var message = "exporting metadata" - internal func export(healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws { + internal func export(_ healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws { for exportTarget in exportTargets { - try exportTarget.writeMetaData(creationDate: NSDate(), profileName: exportConfiguration.profileName, version:"1.0.0") + try exportTarget.writeMetaData(creationDate: Date(), profileName: exportConfiguration.profileName, version:"1.0.0") } } } @@ -55,23 +55,23 @@ internal class UserDataExporter: BaseDataExporter, DataExporter { internal var message = "exporting user data" - internal func export(healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws { + internal func export(_ healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws { var userData = Dictionary() if let birthDay = try? healthStore.dateOfBirth() { - userData[HealthKitConstants.DATE_OF_BIRTH] = birthDay + userData[HealthKitConstants.DATE_OF_BIRTH] = birthDay as AnyObject } - if let sex = try? healthStore.biologicalSex() where sex.biologicalSex != HKBiologicalSex.NotSet { - userData[HealthKitConstants.BIOLOGICAL_SEX] = sex.biologicalSex.rawValue + if let sex = try? healthStore.biologicalSex(), sex.biologicalSex != HKBiologicalSex.notSet { + userData[HealthKitConstants.BIOLOGICAL_SEX] = sex.biologicalSex.rawValue as AnyObject } - if let bloodType = try? healthStore.bloodType() where bloodType.bloodType != HKBloodType.NotSet { - userData[HealthKitConstants.BLOOD_TYPE] = bloodType.bloodType.rawValue + if let bloodType = try? healthStore.bloodType(), bloodType.bloodType != HKBloodType.notSet { + userData[HealthKitConstants.BLOOD_TYPE] = bloodType.bloodType.rawValue as AnyObject } - if let fitzpatrick = try? healthStore.fitzpatrickSkinType() where fitzpatrick.skinType != HKFitzpatrickSkinType.NotSet { - userData[HealthKitConstants.FITZPATRICK_SKIN_TYPE] = fitzpatrick.skinType.rawValue + if let fitzpatrick = try? healthStore.fitzpatrickSkinType(), fitzpatrick.skinType != HKFitzpatrickSkinType.notSet { + userData[HealthKitConstants.FITZPATRICK_SKIN_TYPE] = fitzpatrick.skinType.rawValue as AnyObject } for exportTarget in exportTargets { @@ -96,26 +96,26 @@ internal class QuantityTypeDataExporter: BaseDataExporter, DataExporter { super.init(exportConfiguration: exportConfiguration) } - func writeResults(results: [HKSample]?, exportTargets: [ExportTarget], error: NSError?) -> Void { + func writeResults(_ results: [HKSample]?, exportTargets: [ExportTarget], error: NSError?) -> Void { if error != nil { self.healthQueryError = error } else { do { for sample in results as! [HKQuantitySample] { - let value = sample.quantity.doubleValueForUnit(self.unit) + let value = sample.quantity.doubleValue(for: self.unit) for exportTarget in exportTargets { var dict: Dictionary = [:] if exportConfiguration.exportUuids { - dict[HealthKitConstants.UUID] = sample.UUID.UUIDString + dict[HealthKitConstants.UUID] = sample.uuid.uuidString as AnyObject } - dict[HealthKitConstants.S_DATE] = sample.startDate - dict[HealthKitConstants.VALUE] = value - dict[HealthKitConstants.UNIT] = unit.description + dict[HealthKitConstants.S_DATE] = sample.startDate as AnyObject + dict[HealthKitConstants.VALUE] = value as AnyObject + dict[HealthKitConstants.UNIT] = unit.description as AnyObject if sample.startDate != sample.endDate { - dict[HealthKitConstants.E_DATE] = sample.endDate + dict[HealthKitConstants.E_DATE] = sample.endDate as AnyObject } try exportTarget.writeDictionary(dict); } @@ -126,9 +126,9 @@ internal class QuantityTypeDataExporter: BaseDataExporter, DataExporter { } } - func anchorQuery(healthStore: HKHealthStore, exportTargets: [ExportTarget], anchor : HKQueryAnchor?) throws -> (anchor:HKQueryAnchor?, count:Int?) { + func anchorQuery(_ healthStore: HKHealthStore, exportTargets: [ExportTarget], anchor : HKQueryAnchor?) throws -> (anchor:HKQueryAnchor?, count:Int?) { - let semaphore = dispatch_semaphore_create(0) + let semaphore = DispatchSemaphore(value: 0) var resultAnchor: HKQueryAnchor? var resultCount: Int? let query = HKAnchoredObjectQuery( @@ -137,16 +137,16 @@ internal class QuantityTypeDataExporter: BaseDataExporter, DataExporter { anchor: anchor , limit: queryCountLimit) { (query, results, deleted, newAnchor, error) -> Void in - self.writeResults(results, exportTargets: exportTargets, error: error) + self.writeResults(results, exportTargets: exportTargets, error: error as! NSError) resultAnchor = newAnchor resultCount = results?.count - dispatch_semaphore_signal(semaphore) + semaphore.signal() } - healthStore.executeQuery(query) + healthStore.execute(query) - dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) + semaphore.wait(timeout: DispatchTime.distantFuture) try rethrowCollectedErrors() @@ -154,7 +154,7 @@ internal class QuantityTypeDataExporter: BaseDataExporter, DataExporter { } - internal func export(healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws { + internal func export(_ healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws { for exportTarget in exportTargets { try exportTarget.startWriteType(type) } @@ -183,7 +183,7 @@ internal class CategoryTypeDataExporter: BaseDataExporter, DataExporter { super.init(exportConfiguration: exportConfiguration) } - func writeResults(results: [HKCategorySample], exportTargets: [ExportTarget], error: NSError?) -> Void { + func writeResults(_ results: [HKCategorySample], exportTargets: [ExportTarget], error: NSError?) -> Void { if error != nil { self.healthQueryError = error } else { @@ -193,12 +193,12 @@ internal class CategoryTypeDataExporter: BaseDataExporter, DataExporter { for exportTarget in exportTargets { var dict: Dictionary = [:] if exportConfiguration.exportUuids { - dict[HealthKitConstants.UUID] = sample.UUID.UUIDString + dict[HealthKitConstants.UUID] = sample.uuid.uuidString as AnyObject } - dict[HealthKitConstants.S_DATE] = sample.startDate - dict[HealthKitConstants.VALUE] = sample.value + dict[HealthKitConstants.S_DATE] = sample.startDate as AnyObject + dict[HealthKitConstants.VALUE] = sample.value as AnyObject if sample.startDate != sample.endDate { - dict[HealthKitConstants.E_DATE] = sample.endDate + dict[HealthKitConstants.E_DATE] = sample.endDate as AnyObject } try exportTarget.writeDictionary(dict); } @@ -209,9 +209,9 @@ internal class CategoryTypeDataExporter: BaseDataExporter, DataExporter { } } - func anchorQuery(healthStore: HKHealthStore, exportTargets: [ExportTarget], anchor : HKQueryAnchor?) throws -> (anchor:HKQueryAnchor?, count:Int?) { + func anchorQuery(_ healthStore: HKHealthStore, exportTargets: [ExportTarget], anchor : HKQueryAnchor?) throws -> (anchor:HKQueryAnchor?, count:Int?) { - let semaphore = dispatch_semaphore_create(0) + let semaphore = DispatchSemaphore(value: 0) var resultAnchor: HKQueryAnchor? var resultCount: Int? let query = HKAnchoredObjectQuery( @@ -220,16 +220,16 @@ internal class CategoryTypeDataExporter: BaseDataExporter, DataExporter { anchor: anchor , limit: queryCountLimit) { (query, results, deleted, newAnchor, error) -> Void in - self.writeResults(results as! [HKCategorySample], exportTargets: exportTargets, error: error) + self.writeResults(results as! [HKCategorySample], exportTargets: exportTargets, error: error as! NSError) resultAnchor = newAnchor resultCount = results?.count - dispatch_semaphore_signal(semaphore) + semaphore.signal() } - healthStore.executeQuery(query) + healthStore.execute(query) - dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) + semaphore.wait(timeout: DispatchTime.distantFuture) try rethrowCollectedErrors() @@ -237,7 +237,7 @@ internal class CategoryTypeDataExporter: BaseDataExporter, DataExporter { } - internal func export(healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws { + internal func export(_ healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws { for exportTarget in exportTargets { try exportTarget.startWriteType(type) } @@ -267,7 +267,7 @@ internal class CorrelationTypeDataExporter: BaseDataExporter, DataExporter { super.init(exportConfiguration: exportConfiguration) } - func writeResults(results: [HKCorrelation], exportTargets: [ExportTarget], error: NSError?) -> Void { + func writeResults(_ results: [HKCorrelation], exportTargets: [ExportTarget], error: NSError?) -> Void { if error != nil { self.healthQueryError = error } else { @@ -276,11 +276,11 @@ internal class CorrelationTypeDataExporter: BaseDataExporter, DataExporter { var dict: Dictionary = [:] if exportConfiguration.exportUuids { - dict[HealthKitConstants.UUID] = sample.UUID.UUIDString + dict[HealthKitConstants.UUID] = sample.uuid.uuidString as AnyObject } - dict[HealthKitConstants.S_DATE] = sample.startDate + dict[HealthKitConstants.S_DATE] = sample.startDate as AnyObject if sample.startDate != sample.endDate { - dict[HealthKitConstants.E_DATE] = sample.endDate + dict[HealthKitConstants.E_DATE] = sample.endDate as AnyObject } var subSampleArray:[AnyObject] = [] @@ -289,30 +289,30 @@ internal class CorrelationTypeDataExporter: BaseDataExporter, DataExporter { var sampleDict: Dictionary = [:] if exportConfiguration.exportUuids { - sampleDict[HealthKitConstants.UUID] = subsample.UUID.UUIDString + sampleDict[HealthKitConstants.UUID] = subsample.uuid.uuidString as AnyObject } - sampleDict[HealthKitConstants.S_DATE] = subsample.startDate + sampleDict[HealthKitConstants.S_DATE] = subsample.startDate as AnyObject if subsample.startDate != subsample.endDate { - sampleDict[HealthKitConstants.E_DATE] = subsample.endDate + sampleDict[HealthKitConstants.E_DATE] = subsample.endDate as AnyObject } - sampleDict[HealthKitConstants.TYPE] = subsample.sampleType.identifier + sampleDict[HealthKitConstants.TYPE] = subsample.sampleType.identifier as AnyObject if let quantitySample = subsample as? HKQuantitySample { let unit = self.typeMap[quantitySample.quantityType]! - sampleDict[HealthKitConstants.UNIT] = unit.description - sampleDict[HealthKitConstants.VALUE] = quantitySample.quantity.doubleValueForUnit(unit) + sampleDict[HealthKitConstants.UNIT] = unit.description as AnyObject + sampleDict[HealthKitConstants.VALUE] = quantitySample.quantity.doubleValue(for: unit) as AnyObject } else if let categorySample = subsample as? HKCategorySample { - sampleDict[HealthKitConstants.VALUE] = categorySample.value + sampleDict[HealthKitConstants.VALUE] = categorySample.value as AnyObject } else { - throw ExportError.IllegalArgumentError("unsupported correlation type \(subsample.sampleType.identifier)") + throw ExportError.illegalArgumentError("unsupported correlation type \(subsample.sampleType.identifier)") } - subSampleArray.append(sampleDict) + subSampleArray.append(sampleDict as AnyObject) } - dict[HealthKitConstants.OBJECTS] = subSampleArray + dict[HealthKitConstants.OBJECTS] = subSampleArray as AnyObject for exportTarget in exportTargets { try exportTarget.writeDictionary(dict); @@ -325,9 +325,9 @@ internal class CorrelationTypeDataExporter: BaseDataExporter, DataExporter { } } - func anchorQuery(healthStore: HKHealthStore, exportTargets: [ExportTarget], anchor : HKQueryAnchor?) throws -> (anchor:HKQueryAnchor?, count:Int?) { + func anchorQuery(_ healthStore: HKHealthStore, exportTargets: [ExportTarget], anchor : HKQueryAnchor?) throws -> (anchor:HKQueryAnchor?, count:Int?) { - let semaphore = dispatch_semaphore_create(0) + let semaphore = DispatchSemaphore(value: 0) var resultAnchor: HKQueryAnchor? var resultCount: Int? let query = HKAnchoredObjectQuery( @@ -337,23 +337,23 @@ internal class CorrelationTypeDataExporter: BaseDataExporter, DataExporter { limit: queryCountLimit) { (query, results, deleted, newAnchor, error) -> Void in - self.writeResults(results as! [HKCorrelation], exportTargets: exportTargets, error: error) + self.writeResults(results as! [HKCorrelation], exportTargets: exportTargets, error: error as! NSError) resultAnchor = newAnchor resultCount = results?.count - dispatch_semaphore_signal(semaphore) + semaphore.signal() } - healthStore.executeQuery(query) + healthStore.execute(query) - dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) + semaphore.wait(timeout: DispatchTime.distantFuture) try rethrowCollectedErrors() return (anchor:resultAnchor, count: resultCount) } - internal func export(healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws { + internal func export(_ healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws { for exportTarget in exportTargets { try exportTarget.startWriteType(type) } @@ -375,7 +375,7 @@ internal class CorrelationTypeDataExporter: BaseDataExporter, DataExporter { internal class WorkoutDataExporter: BaseDataExporter, DataExporter { internal var message = "exporting workouts data" - func writeResults(results: [HKWorkout], exportTargets:[ExportTarget], error: NSError?) -> Void { + func writeResults(_ results: [HKWorkout], exportTargets:[ExportTarget], error: NSError?) -> Void { if error != nil { self.healthQueryError = error } else { @@ -388,27 +388,27 @@ internal class WorkoutDataExporter: BaseDataExporter, DataExporter { var dict: Dictionary = [:] if exportConfiguration.exportUuids { - dict[HealthKitConstants.UUID] = sample.UUID.UUIDString + dict[HealthKitConstants.UUID] = sample.uuid.uuidString as AnyObject } - dict[HealthKitConstants.WORKOUT_ACTIVITY_TYPE] = sample.workoutActivityType.rawValue - dict[HealthKitConstants.S_DATE] = sample.startDate + dict[HealthKitConstants.WORKOUT_ACTIVITY_TYPE] = sample.workoutActivityType.rawValue as AnyObject + dict[HealthKitConstants.S_DATE] = sample.startDate as AnyObject if sample.startDate != sample.endDate { - dict[HealthKitConstants.E_DATE] = sample.endDate + dict[HealthKitConstants.E_DATE] = sample.endDate as AnyObject } - dict[HealthKitConstants.DURATION] = sample.duration // seconds - dict[HealthKitConstants.TOTAL_DISTANCE] = sample.totalDistance?.doubleValueForUnit(HKUnit.meterUnit()) - dict[HealthKitConstants.TOTAL_ENERGY_BURNED] = sample.totalEnergyBurned?.doubleValueForUnit(HKUnit.kilocalorieUnit()) + dict[HealthKitConstants.DURATION] = sample.duration as AnyObject // seconds + dict[HealthKitConstants.TOTAL_DISTANCE] = sample.totalDistance?.doubleValue(for: HKUnit.meter()) as AnyObject + dict[HealthKitConstants.TOTAL_ENERGY_BURNED] = sample.totalEnergyBurned?.doubleValue(for: HKUnit.kilocalorie()) as AnyObject var workoutEvents: [Dictionary] = [] for event in sample.workoutEvents ?? [] { var workoutEvent: Dictionary = [:] - workoutEvent[HealthKitConstants.TYPE] = event.type.rawValue - workoutEvent[HealthKitConstants.S_DATE] = event.date + workoutEvent[HealthKitConstants.TYPE] = event.type.rawValue as AnyObject + workoutEvent[HealthKitConstants.S_DATE] = event.date as AnyObject workoutEvents.append(workoutEvent) } - dict[HealthKitConstants.WORKOUT_EVENTS] = workoutEvents + dict[HealthKitConstants.WORKOUT_EVENTS] = workoutEvents as AnyObject for exportTarget in exportTargets { try exportTarget.writeDictionary(dict); @@ -426,20 +426,20 @@ internal class WorkoutDataExporter: BaseDataExporter, DataExporter { } - internal func export(healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws { + internal func export(_ healthStore: HKHealthStore, exportTargets: [ExportTarget]) throws { - let semaphore = dispatch_semaphore_create(0) + let semaphore = DispatchSemaphore(value: 0) let query = HKSampleQuery(sampleType: HKObjectType.workoutType(), predicate: exportConfiguration.getPredicate(), limit: Int(HKObjectQueryNoLimit), sortDescriptors: [sortDescriptor]) { (query, results, error) -> Void in - self.writeResults(results as! [HKWorkout], exportTargets:exportTargets, error:error) - dispatch_semaphore_signal(semaphore) + self.writeResults(results as! [HKWorkout], exportTargets:exportTargets, error:error as! NSError) + semaphore.signal() } - healthStore.executeQuery(query) + healthStore.execute(query) // wait for asyn call to complete - dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) + semaphore.wait(timeout: DispatchTime.distantFuture) try rethrowCollectedErrors() } -} \ No newline at end of file +} diff --git a/Pod/Classes/HealthKitDataImporter.swift b/Pod/Classes/HealthKitDataImporter.swift index b8711bf..359eb7f 100644 --- a/Pod/Classes/HealthKitDataImporter.swift +++ b/Pod/Classes/HealthKitDataImporter.swift @@ -24,7 +24,7 @@ class MetaDataOutputJsonHandler: DefaultJsonHandler { return metaDataDict } - override func name(name: String) { + override func name(_ name: String) { self.name = name } @@ -39,12 +39,12 @@ class MetaDataOutputJsonHandler: DefaultJsonHandler { } } - override func stringValue(value: String){ + override func stringValue(_ value: String){ if collectProperties { - metaDataDict[name!] = value + metaDataDict[name!] = value as AnyObject } } - override func numberValue(value: NSNumber){ + override func numberValue(_ value: NSNumber){ if collectProperties { metaDataDict[name!] = value } @@ -75,48 +75,48 @@ class SampleOutputJsonHandler: JsonHandlerProtocol { self.parent = parent } - func put(key:String, value: AnyObject?) { + func put(_ key:String, value: AnyObject?) { dict[key] = value } - func createArrayContext(name: String) -> SampleContext { - let sc = SampleContext(parent: self, type: .ARRAY) + func createArrayContext(_ name: String) -> SampleContext { + let sc = SampleContext(parent: self, type: .array) sc.name = name childs.append(sc) return sc } func createObjectContext() -> SampleContext { - let sc = SampleContext(parent: self, type: .OBJECT) + let sc = SampleContext(parent: self, type: .object) childs.append(sc) return sc } func getStructureAsDict() -> AnyObject { - if type == .ARRAY { + if type == .array { var result:[AnyObject] = [] for child in childs { result.append(child.getStructureAsDict()) } - return result; + return result as AnyObject; } var resultDict = dict for child in childs { - if child.type == .ARRAY { + if child.type == .array { resultDict[child.name!] = child.getStructureAsDict() as AnyObject! } } - return resultDict + return resultDict as AnyObject } } - internal func printWithLevel(level:Int, string:String){ + internal func printWithLevel(_ level:Int, string:String){ var outString = "\(level)" - for var i=0; i Void + let onSample : (_ sample: AnyObject, _ typeName:String) -> Void /// save the lastname to decide what is a sample and what is the name of a value var lastName = "" /// a samplecontext - created for evenry new sample @@ -134,16 +134,16 @@ class SampleOutputJsonHandler: JsonHandlerProtocol { /// the healthkit sample type that is currently processed var hkTypeName: String? = nil - init(onSample: (sample: AnyObject, typeName:String) -> Void) { + init(onSample: @escaping (_ sample: AnyObject, _ typeName:String) -> Void) { self.onSample = onSample } - func name(name: String) { + func name(_ name: String) { lastName = name } func startArray() { - level++ + level += 1 if level == 2 && lastName.hasPrefix("HK") { hkTypeName = lastName } @@ -157,17 +157,17 @@ class SampleOutputJsonHandler: JsonHandlerProtocol { if level == 2 { hkTypeName = nil } - level-- + level -= 1 sampleContext = sampleContext == nil ? nil : sampleContext!.parent } func startObject() { - level++ + level += 1 if level == 3 { // a new HKSample starts - sampleContext = SampleContext(parent: nil, type: .OBJECT) + sampleContext = SampleContext(parent: nil, type: .object) sampleContext?.name = hkTypeName } @@ -179,26 +179,26 @@ class SampleOutputJsonHandler: JsonHandlerProtocol { func endObject() { if level == 3 { // the HKSample ends - onSample(sample: sampleContext!.getStructureAsDict(), typeName:hkTypeName!) + onSample(sampleContext!.getStructureAsDict(), hkTypeName!) sampleContext = nil } sampleContext = sampleContext == nil ? nil : sampleContext!.parent - level-- + level -= 1 } - func stringValue(value: String){ + func stringValue(_ value: String){ if sampleContext != nil { - sampleContext!.put(lastName, value:value) + sampleContext!.put(lastName, value:value as AnyObject) } } - func boolValue(value: Bool){ + func boolValue(_ value: Bool){ if sampleContext != nil { - sampleContext!.put(lastName, value:value) + sampleContext!.put(lastName, value:value as AnyObject) } } - func numberValue(value: NSNumber){ + func numberValue(_ value: NSNumber){ if sampleContext != nil { sampleContext!.put(lastName, value:value) } @@ -213,4 +213,4 @@ class SampleOutputJsonHandler: JsonHandlerProtocol { func shouldCancelReadingTheJson() -> Bool { return false } -} \ No newline at end of file +} diff --git a/Pod/Classes/HealthKitProfile.swift b/Pod/Classes/HealthKitProfile.swift index c8468d1..41e07f8 100644 --- a/Pod/Classes/HealthKitProfile.swift +++ b/Pod/Classes/HealthKitProfile.swift @@ -9,30 +9,30 @@ import Foundation import HealthKit ///MetaData of a profile -public class HealthKitProfileMetaData { +open class HealthKitProfileMetaData { /// the name of the profile - private(set) public var profileName: String? + fileprivate(set) open var profileName: String? /// the date the profie was exported - private(set) public var creationDate: NSDate? + fileprivate(set) open var creationDate: Date? /// the version of the profile - private(set) public var version: String? + fileprivate(set) open var version: String? /// the type of the profile - private(set) public var type: String? + fileprivate(set) open var type: String? } /// a healthkit Profile - can be used to read data from the profile and import the profile into the healthkit store. -public class HealthKitProfile : CustomStringConvertible { +open class HealthKitProfile : CustomStringConvertible { - let fileAtPath: NSURL + let fileAtPath: URL /// the name of the profile file - without any path components - private(set) public var fileName: String + fileprivate(set) open var fileName: String /// the size of the profile file in bytes - private(set) public var fileSize:UInt64? + fileprivate(set) open var fileSize:UInt64? - let fileReadQueue = NSOperationQueue() + let fileReadQueue = OperationQueue() /// for textual representation of this object - public var description: String { + open var description: String { return "\(fileName) \(fileSize)" } @@ -40,12 +40,12 @@ public class HealthKitProfile : CustomStringConvertible { constructor for aprofile - Parameter fileAtPath: the Url of the profile in the file system */ - public init(fileAtPath: NSURL){ + public init(fileAtPath: URL){ fileReadQueue.maxConcurrentOperationCount = 1 - fileReadQueue.qualityOfService = NSQualityOfService.UserInteractive + fileReadQueue.qualityOfService = QualityOfService.userInteractive self.fileAtPath = fileAtPath - self.fileName = self.fileAtPath.lastPathComponent! - let attr:NSDictionary? = try! NSFileManager.defaultManager().attributesOfItemAtPath(fileAtPath.path!) + self.fileName = self.fileAtPath.lastPathComponent + let attr:NSDictionary? = try! FileManager.default.attributesOfItem(atPath: fileAtPath.path) as NSDictionary if let _attr = attr { self.fileSize = _attr.fileSize(); } @@ -60,12 +60,12 @@ public class HealthKitProfile : CustomStringConvertible { let result = HealthKitProfileMetaData() let metaDataOutput = MetaDataOutputJsonHandler() - JsonReader.readFileAtPath(self.fileAtPath.path!, withJsonHandler: metaDataOutput) + JsonReader.readFileAtPath(self.fileAtPath.path, withJsonHandler: metaDataOutput) let metaData = metaDataOutput.getMetaData() if let dateTime = metaData["creationDate"] as? NSNumber { - result.creationDate = NSDate(timeIntervalSince1970: dateTime.doubleValue/1000) + result.creationDate = Date(timeIntervalSince1970: dateTime.doubleValue/1000) } result.profileName = metaData["profileName"] as? String @@ -81,14 +81,14 @@ public class HealthKitProfile : CustomStringConvertible { - Parameter asynchronous: if true the metsdata wil be read asynchronously. If false the read will be synchronous. - Parameter callback: is called if the meatdat have been read. */ - public func loadMetaData(asynchronous:Bool, callback:(metaData: HealthKitProfileMetaData) -> Void ){ + open func loadMetaData(_ asynchronous:Bool, callback:@escaping (_ metaData: HealthKitProfileMetaData) -> Void ){ if asynchronous { - fileReadQueue.addOperationWithBlock(){ - callback(metaData: self.loadMetaData()) + fileReadQueue.addOperation(){ + callback(self.loadMetaData()) } } else { - callback(metaData: loadMetaData()) + callback(loadMetaData()) } } @@ -96,7 +96,7 @@ public class HealthKitProfile : CustomStringConvertible { Reads all samples from the profile and fires the callback onSample on every sample. - Parameter onSample: the callback is called on every sample. */ - func importSamples(onSample: (sample: HKSample) -> Void) throws { + func importSamples(_ onSample: @escaping (_ sample: HKSample) -> Void) throws { let sampleImportHandler = SampleOutputJsonHandler(){ (sampleDict:AnyObject, typeName: String) in @@ -104,18 +104,18 @@ public class HealthKitProfile : CustomStringConvertible { if let creator = SampleCreatorRegistry.get(typeName) { let sampleOpt:HKSample? = creator.createSample(sampleDict) if let sample = sampleOpt { - onSample(sample: sample) + onSample(sample) } } } - JsonReader.readFileAtPath(self.fileAtPath.path!, withJsonHandler: sampleImportHandler) + JsonReader.readFileAtPath(self.fileAtPath.path, withJsonHandler: sampleImportHandler) } /** removes the profile from the file system */ - public func deleteFile() throws { - try NSFileManager.defaultManager().removeItemAtPath(fileAtPath.path!) + open func deleteFile() throws { + try FileManager.default.removeItem(atPath: fileAtPath.path) } -} \ No newline at end of file +} diff --git a/Pod/Classes/HealthKitProfileImporter.swift b/Pod/Classes/HealthKitProfileImporter.swift index 6bfb52a..bb9f09b 100644 --- a/Pod/Classes/HealthKitProfileImporter.swift +++ b/Pod/Classes/HealthKitProfileImporter.swift @@ -10,24 +10,24 @@ import Foundation import HealthKit /// errors the importer can create -public enum ImportError: ErrorType { +public enum ImportError: Error { /// the type of the profle is not supported - case UnsupportedType(String) + case unsupportedType(String) /// HealthKit is not available on the device - case HealthDataNotAvailable + case healthDataNotAvailable } /// importer for a healthkit profile -public class HealthKitProfileImporter { +open class HealthKitProfileImporter { let healthStore: HKHealthStore - let importQueue = NSOperationQueue() + let importQueue = OperationQueue() /// provide your instance of the HKHealthStore public init(healthStore: HKHealthStore) { self.healthStore = healthStore self.importQueue.maxConcurrentOperationCount = 1 - self.importQueue.qualityOfService = NSQualityOfService.UserInteractive + self.importQueue.qualityOfService = QualityOfService.userInteractive } /** @@ -38,28 +38,28 @@ public class HealthKitProfileImporter { - Parameter onProgress: callback for progress messages - Parameter onCompletion: callback if the import has finished. The error is nl if everything went well. */ - public func importProfile ( - profile: HealthKitProfile, + open func importProfile ( + _ profile: HealthKitProfile, deleteExistingData: Bool, - onProgress: (message: String, progressInPercent: NSNumber?)->Void, - onCompletion: (error: ErrorType?)-> Void) { + onProgress: @escaping (_ message: String, _ progressInPercent: NSNumber?)->Void, + onCompletion: @escaping (_ error: Error?)-> Void) { if !HKHealthStore.isHealthDataAvailable() { - onCompletion(error:ImportError.HealthDataNotAvailable) + onCompletion(ImportError.healthDataNotAvailable) return } - healthStore.requestAuthorizationToShareTypes(HealthKitConstants.authorizationWriteTypes(), readTypes: nil) { + healthStore.requestAuthorization(toShare: HealthKitConstants.authorizationWriteTypes(), read: nil) { (success, error) -> Void in /// TODO success error handling - self.importQueue.addOperationWithBlock(){ + self.importQueue.addOperation(){ // check that the type is one pf the supported profile types let metaData = profile.loadMetaData() - let strExpectedType = String(JsonSingleDocExportTarget) + let strExpectedType = String(describing: JsonSingleDocExportTarget.self) if metaData.type != strExpectedType { - onCompletion(error: ImportError.UnsupportedType("\(strExpectedType) is only supported")) + onCompletion(ImportError.unsupportedType("\(strExpectedType) is only supported")) return } @@ -67,37 +67,37 @@ public class HealthKitProfileImporter { if deleteExistingData { HealthKitStoreCleaner(healthStore: self.healthStore).clean(){(message:String, progressInPercent: Double?) in - onProgress(message: message, progressInPercent: progressInPercent == nil ? nil : progressInPercent!/2) + onProgress(message, progressInPercent == nil ? nil : NSNumber(value: progressInPercent!/2)) } } - onProgress(message: "Start importing", progressInPercent: nil) + onProgress("Start importing", nil) var lastSampleType = "" try! profile.importSamples(){ (sample: HKSample) in //print(sample) - if lastSampleType != String(sample.sampleType) { - lastSampleType = String(sample.sampleType) - onProgress(message: "importing \(lastSampleType)", progressInPercent: nil) + if lastSampleType != String(describing: sample.sampleType) { + lastSampleType = String(describing: sample.sampleType) + onProgress("importing \(lastSampleType)", nil) } - self.healthStore.saveObject(sample){ - (success:Bool, error:NSError?) in + self.healthStore.save(sample, withCompletion: { + (success:Bool, error:Error?) in /// TODO success error handling print(success, error) if !success { print(error) } - } + }) } - onProgress(message: "Import done", progressInPercent: 1.0) + onProgress("Import done", 1.0) - onCompletion(error:nil) + onCompletion(nil) } } } -} \ No newline at end of file +} diff --git a/Pod/Classes/HealthKitProfileReader.swift b/Pod/Classes/HealthKitProfileReader.swift index f51984c..10bcb30 100644 --- a/Pod/Classes/HealthKitProfileReader.swift +++ b/Pod/Classes/HealthKitProfileReader.swift @@ -9,20 +9,20 @@ import Foundation /// Utility class to generate Profiles from files in a directory -public class HealthKitProfileReader { +open class HealthKitProfileReader { /** Creates an array of profiles that are stored in a folder - Parameter folder: Url of the folder - Returns: an array of HealthKitProfile objects */ - public static func readProfilesFromDisk(folder: NSURL) -> [HealthKitProfile]{ + open static func readProfilesFromDisk(_ folder: URL) -> [HealthKitProfile]{ var profiles:[HealthKitProfile] = [] - let enumerator = NSFileManager.defaultManager().enumeratorAtPath(folder.path!) + let enumerator = FileManager.default.enumerator(atPath: folder.path) for file in enumerator! { - let pathUrl = folder.URLByAppendingPathComponent(file as! String) - if NSFileManager.defaultManager().isReadableFileAtPath(pathUrl.path!) && pathUrl.pathExtension == "hsg" { + let pathUrl = folder.appendingPathComponent(file as! String) + if FileManager.default.isReadableFile(atPath: pathUrl.path) && pathUrl.pathExtension == "hsg" { profiles.append(HealthKitProfile(fileAtPath:pathUrl)) } } @@ -30,4 +30,4 @@ public class HealthKitProfileReader { return profiles } -} \ No newline at end of file +} diff --git a/Pod/Classes/HealthKitStoreCleaner.swift b/Pod/Classes/HealthKitStoreCleaner.swift index 972e18f..9842017 100644 --- a/Pod/Classes/HealthKitStoreCleaner.swift +++ b/Pod/Classes/HealthKitStoreCleaner.swift @@ -8,6 +8,30 @@ import Foundation import HealthKit +// FIXME: comparison operators with optionals were removed from the Swift Standard Libary. +// Consider refactoring the code to use the non-optional operators. +fileprivate func < (lhs: T?, rhs: T?) -> Bool { + switch (lhs, rhs) { + case let (l?, r?): + return l < r + case (nil, _?): + return true + default: + return false + } +} + +// FIXME: comparison operators with optionals were removed from the Swift Standard Libary. +// Consider refactoring the code to use the non-optional operators. +fileprivate func > (lhs: T?, rhs: T?) -> Bool { + switch (lhs, rhs) { + case let (l?, r?): + return l > r + default: + return rhs < lhs + } +} + class HealthKitStoreCleaner { @@ -27,18 +51,18 @@ class HealthKitStoreCleaner { Cleans all HealthKIt data from the healthkit store that are created by this app. - Parameter onProgress: callback that informs about the cleaning progress */ - func clean( onProgress: (message: String, progressInPercent: Double?)->Void){ + func clean( _ onProgress: (_ message: String, _ progressInPercent: Double?)->Void){ - let source = HKSource.defaultSource() - let predicate = HKQuery.predicateForObjectsFromSource(source) + let source = HKSource.default() + let predicate = HKQuery.predicateForObjects(from: source) let allTypes = HealthKitConstants.authorizationWriteTypes() for type in allTypes { - let semaphore = dispatch_semaphore_create(0) + let semaphore = DispatchSemaphore(value: 0) - onProgress(message: "deleting \(type)", progressInPercent: nil) + onProgress("deleting \(type)", nil) let queryCountLimit = 1000 var result : (anchor:HKQueryAnchor?, count:Int?) = (anchor:nil, count: -1) @@ -51,30 +75,30 @@ class HealthKitStoreCleaner { (query, results, deleted, newAnchor, error) -> Void in if results?.count > 0 { - self.healthStore.deleteObjects(results!){ - (success:Bool, error:NSError?) -> Void in + self.healthStore.delete(results!, withCompletion: { + (success:Bool, error:Error?) -> Void in if success { print("deleted \(results?.count) from \(type)") } else { print("error deleting from \(type): \(error)") } - dispatch_semaphore_signal(semaphore) - } + semaphore.signal() + }) } else { - dispatch_semaphore_signal(semaphore) + semaphore.signal() } result.anchor = newAnchor result.count = results?.count } - healthStore.executeQuery(query) + healthStore.execute(query) - dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) + semaphore.wait(timeout: DispatchTime.distantFuture) } while result.count != 0 || result.count==queryCountLimit } } -} \ No newline at end of file +} diff --git a/Pod/Classes/JsonReader.swift b/Pod/Classes/JsonReader.swift index 798a39d..b373057 100644 --- a/Pod/Classes/JsonReader.swift +++ b/Pod/Classes/JsonReader.swift @@ -18,10 +18,10 @@ internal class JsonReader { - Parameter jsonString: the json string that should be read. - Returns: an Object of type AnyObject that the json string defines. */ - static func toJsonObject(jsonString: String) -> AnyObject { - let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding)! - let result = try! NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) - return result + static func toJsonObject(_ jsonString: String) -> AnyObject { + let data = jsonString.data(using: String.Encoding.utf8)! + let result = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) + return result as AnyObject } /** @@ -30,7 +30,7 @@ internal class JsonReader { - Parameter returnDictForKey: name of the field that should be returned as Dictionary. - Returns: a dictionaray for the key with AnyObject values. */ - static func toJsonObject(jsonString: String, returnDictForKey: String) -> Dictionary { + static func toJsonObject(_ jsonString: String, returnDictForKey: String) -> Dictionary { let keyWithDictInDict = JsonReader.toJsonObject(jsonString) as! Dictionary return keyWithDictInDict[returnDictForKey] as! Dictionary } @@ -41,7 +41,7 @@ internal class JsonReader { - Parameter returnArrayForKey: name of the field that should be returned as an Array. - Returns: an array for the key with AnyObject values. */ - static func toJsonObject(jsonString: String, returnArrayForKey: String) -> [AnyObject] { + static func toJsonObject(_ jsonString: String, returnArrayForKey: String) -> [AnyObject] { let keyWithDictInDict = JsonReader.toJsonObject(jsonString) as! Dictionary return keyWithDictInDict[returnArrayForKey] as! [AnyObject] } @@ -52,19 +52,19 @@ internal class JsonReader { - Parameter withJsonHandler: an object that implements JsonHandlerProtocol to process the json events. */ - static func readFileAtPath(fileAtPath: String, withJsonHandler jsonHandler: JsonHandlerProtocol) -> Void { - let inStream = NSInputStream(fileAtPath: fileAtPath)! + static func readFileAtPath(_ fileAtPath: String, withJsonHandler jsonHandler: JsonHandlerProtocol) -> Void { + let inStream = InputStream(fileAtPath: fileAtPath)! inStream.open() let tokenizer = JsonTokenizer(jsonHandler:jsonHandler) let bufferSize = 4096 - var buffer = Array(count: bufferSize, repeatedValue: 0) + var buffer = Array(repeating: 0, count: bufferSize) while inStream.hasBytesAvailable && !jsonHandler.shouldCancelReadingTheJson() { let bytesRead = inStream.read(&buffer, maxLength: bufferSize) if bytesRead > 0 { - let textFileContents = NSString(bytes: &buffer, length: bytesRead, encoding: NSUTF8StringEncoding) + let textFileContents = NSString(bytes: &buffer, length: bytesRead, encoding: String.Encoding.utf8.rawValue) tokenizer.tokenize(textFileContents as! String) } } @@ -78,7 +78,7 @@ internal class JsonReader { */ internal class JsonReaderContext { var type: JsonContextType - private var parent: JsonReaderContext? + fileprivate var parent: JsonReaderContext? var nameOrObject = "" { didSet { @@ -93,7 +93,7 @@ internal class JsonReaderContext { } init(){ - type = .ROOT + type = .root } convenience init(parent: JsonReaderContext, type: JsonContextType){ @@ -104,12 +104,12 @@ internal class JsonReaderContext { func createArrayContext() -> JsonReaderContext { //print("create array context") - return JsonReaderContext(parent: self, type: .ARRAY) + return JsonReaderContext(parent: self, type: .array) } func createObjectContext() -> JsonReaderContext { //print("create object context") - return JsonReaderContext(parent: self, type: .OBJECT) + return JsonReaderContext(parent: self, type: .object) } func popContext() -> JsonReaderContext { @@ -136,17 +136,17 @@ internal class JsonTokenizer { /** removes the question marks from a string. */ - internal func removeQuestionMarks(str: String) -> String{ + internal func removeQuestionMarks(_ str: String) -> String{ var result = str - result.removeAtIndex(result.startIndex) - result.removeAtIndex(result.endIndex.predecessor()) + result.remove(at: result.startIndex) + result.remove(at: result.characters.index(before: result.endIndex)) return result } /** outputs a name. */ - internal func writeName(context: JsonReaderContext) { + internal func writeName(_ context: JsonReaderContext) { //print("writeName", context.nameOrObject) let name = removeQuestionMarks(context.nameOrObject) jsonHandler.name(name) @@ -157,7 +157,7 @@ internal class JsonTokenizer { /** outputs a value. Value can be a string, a boolean value a null value or a number. */ - internal func writeValue(context: JsonReaderContext){ + internal func writeValue(_ context: JsonReaderContext){ //print("writeValue", context.nameOrObject) let value:String = context.nameOrObject context.nameOrObject = "" @@ -180,9 +180,9 @@ internal class JsonTokenizer { //let number = numberFormatter.numberFromString(value)! if let intValue = Int(value) { - jsonHandler.numberValue(intValue) + jsonHandler.numberValue(NSNumber(value: intValue)) } else if let doubleValue = Double(value) { - jsonHandler.numberValue(doubleValue) + jsonHandler.numberValue(NSNumber(value: doubleValue)) } @@ -209,7 +209,7 @@ internal class JsonTokenizer { /** main tokenizer function. The string may have any size. */ - func tokenize(toTokenize: String) -> Void { + func tokenize(_ toTokenize: String) -> Void { for chr in toTokenize.characters { //print(chr) switch chr { @@ -302,13 +302,13 @@ protocol JsonHandlerProtocol { func endObject() // a name was tokenized - func name(name: String) + func name(_ name: String) // a string value was tokenized - func stringValue(value: String) + func stringValue(_ value: String) // a boolean value was tokenized - func boolValue(value: Bool) + func boolValue(_ value: Bool) // a number was tokenized - func numberValue(value: NSNumber) + func numberValue(_ value: NSNumber) // a null value was tokenized func nullValue() @@ -326,10 +326,10 @@ class DefaultJsonHandler : JsonHandlerProtocol { func startObject(){} func endObject(){} - func name(name: String){} - func stringValue(value: String){} - func boolValue(value: Bool){} - func numberValue(value: NSNumber){} + func name(_ name: String){} + func stringValue(_ value: String){} + func boolValue(_ value: Bool){} + func numberValue(_ value: NSNumber){} func nullValue(){} func shouldCancelReadingTheJson() -> Bool { @@ -372,19 +372,19 @@ class JsonStringOutputJsonHandler: DefaultJsonHandler { jw.writeEndObject() } - override func name(name: String){ + override func name(_ name: String){ jw.writeFieldName(name) } - override func stringValue(value: String) { + override func stringValue(_ value: String) { jw.writeString(value) } - override func numberValue(value: NSNumber) { + override func numberValue(_ value: NSNumber) { jw.writeNumber(value) } - override func boolValue(value: Bool) { + override func boolValue(_ value: Bool) { jw.writeBool(value) } diff --git a/Pod/Classes/JsonWriter.swift b/Pod/Classes/JsonWriter.swift index 4a1bde2..09a4fd5 100644 --- a/Pod/Classes/JsonWriter.swift +++ b/Pod/Classes/JsonWriter.swift @@ -8,20 +8,20 @@ import Foundation -enum JsonWriterError: ErrorType { - case NSJSONSerializationError(String) +enum JsonWriterError: Error { + case nsjsonSerializationError(String) } enum JsonContextType : Int { - case ROOT - case ARRAY - case OBJECT + case root + case array + case object } enum JsonWriterStatus : Int { - case OK - case WILL_NEED_COMMA - case WILL_NEED_COLON + case ok + case will_NEED_COMMA + case will_NEED_COLON } /** @@ -34,7 +34,7 @@ class JsonWriterContext { var startField = false init(){ - type = .ROOT + type = .root } convenience init(parent: JsonWriterContext, type: JsonContextType){ @@ -48,14 +48,14 @@ class JsonWriterContext { */ func createArrayContext() -> JsonWriterContext { writeValue() - return JsonWriterContext(parent: self, type: .ARRAY) + return JsonWriterContext(parent: self, type: .array) } /** creates an object in the current context. */ func createObjectContext() -> JsonWriterContext { writeValue() - return JsonWriterContext(parent: self, type: .OBJECT) + return JsonWriterContext(parent: self, type: .object) } func writeField(){ @@ -63,7 +63,7 @@ class JsonWriterContext { } func writeValue() { - index++ + index += 1 startField = false } @@ -77,22 +77,22 @@ class JsonWriterContext { func willWriteField() -> JsonWriterStatus { if startField { - return .WILL_NEED_COLON + return .will_NEED_COLON } if(index > 0){ - return .WILL_NEED_COMMA + return .will_NEED_COMMA } - return .OK + return .ok } func willWriteValue() -> JsonWriterStatus { if startField { - return .WILL_NEED_COLON + return .will_NEED_COLON } if(index > 0){ - return .WILL_NEED_COMMA + return .will_NEED_COMMA } - return .OK + return .ok } } @@ -151,17 +151,17 @@ internal class JsonWriter { /** Starts writing a field name - a json string that will be written in quotation marks. */ - internal func writeFieldName(name: String) { + internal func writeFieldName(_ name: String) { let status = writerContext.willWriteField() writeCommaOrColon(status) writerContext.writeField() write("\""+name+"\"") } - internal func writeCommaOrColon(status: JsonWriterStatus){ - if status == .WILL_NEED_COMMA { + internal func writeCommaOrColon(_ status: JsonWriterStatus){ + if status == .will_NEED_COMMA { write(",") - } else if status == .WILL_NEED_COLON { + } else if status == .will_NEED_COLON { write(":") } } @@ -169,9 +169,9 @@ internal class JsonWriter { /** Writes a String value. All '"' characters will be escaped. */ - internal func writeString(text: String?) { + internal func writeString(_ text: String?) { if let v = text { - let escapedV = v.stringByReplacingOccurrencesOfString("\"", withString: "\"") + let escapedV = v.replacingOccurrences(of: "\"", with: "\"") let status = writerContext.willWriteValue() writeCommaOrColon(status) writerContext.writeValue() @@ -185,7 +185,7 @@ internal class JsonWriter { Writes a NSNumber. If the NSNumber-object ist a boolean true/false is written to the stream. If the NSNumber is nil null will be written */ - internal func writeNumber(number: NSNumber?) { + internal func writeNumber(_ number: NSNumber?) { if let v = number { let status = writerContext.willWriteValue() writeCommaOrColon(status) @@ -204,7 +204,7 @@ internal class JsonWriter { /** Writes a boolean value to the stream - e.g. true or false. If the value is nil null is written to the stream. */ - internal func writeBool(value: Bool?) { + internal func writeBool(_ value: Bool?) { if let v = value { let status = writerContext.willWriteValue() writeCommaOrColon(status) @@ -218,9 +218,9 @@ internal class JsonWriter { /** Writes an NSDate object to the strem. JSON did not support a date value. Instead the milliseconds since 01.01.1970 will be used. */ - internal func writeDate(value: NSDate?) { + internal func writeDate(_ value: Date?) { if let date = value { - let number = NSNumber(double:date.timeIntervalSince1970*1000) + let number = NSNumber(value: date.timeIntervalSince1970*1000 as Double) writeNumber(number) } else { writeNull() @@ -246,20 +246,20 @@ internal class JsonWriter { - Throws: JsonWriterError if a value is of unsupported type. */ - internal func writeObject(anyObject: AnyObject) throws { - if let array = anyObject as? [AnyObject] { + internal func writeObject(_ anyObject: Any) throws { + if let array = anyObject as? [Any] { writeStartArray() for element in array { if let strValue = element as? String { writeString(strValue) } else if let numberValue = element as? NSNumber { writeNumber(numberValue) - } else if let dateValue = element as? NSDate { + } else if let dateValue = element as? Date { writeDate(dateValue) } else if let dictValue = element as? Dictionary { - try writeObject(dictValue) + try writeObject(dictValue as AnyObject) } else { - throw JsonWriterError.NSJSONSerializationError("unsupported value type: \(element.dynamicType)") + throw JsonWriterError.nsjsonSerializationError("unsupported value type: \(type(of: element))") } } writeEndArray() @@ -272,18 +272,18 @@ internal class JsonWriter { writeField(key, value: strValue) } else if let numberValue = value as? NSNumber { writeField(key, value: numberValue) - } else if let dateValue = value as? NSDate { + } else if let dateValue = value as? Date { writeField(key, value: dateValue) } else if let arrayValue = value as? NSArray { writeFieldName(key) try writeObject(arrayValue) } else { - throw JsonWriterError.NSJSONSerializationError("unsupported value type: \(value.dynamicType)") + throw JsonWriterError.nsjsonSerializationError("unsupported value type: \(type(of: value))") } } writeEndObject() }else { - throw JsonWriterError.NSJSONSerializationError("unsupported value type: \(anyObject.dynamicType)") + throw JsonWriterError.nsjsonSerializationError("unsupported value type: \(type(of: anyObject))") } } @@ -292,7 +292,7 @@ internal class JsonWriter { - Parameter fieldName: The name of the field - Parameter value: The String value */ - internal func writeField(fieldName: String, value: String?) { + internal func writeField(_ fieldName: String, value: String?) { writeFieldName(fieldName) writeString(value) } @@ -302,7 +302,7 @@ internal class JsonWriter { - Parameter fieldName: The name of the field - Parameter value: The Bool value */ - internal func writeField(fieldName: String, value: Bool?) { + internal func writeField(_ fieldName: String, value: Bool?) { writeFieldName(fieldName) writeBool(value) } @@ -312,7 +312,7 @@ internal class JsonWriter { - Parameter fieldName: The name of the field - Parameter value: The NSNumber value */ - internal func writeField(fieldName: String, value: NSNumber?) { + internal func writeField(_ fieldName: String, value: NSNumber?) { writeFieldName(fieldName) writeNumber(value) } @@ -322,7 +322,7 @@ internal class JsonWriter { - Parameter fieldName: The name of the field - Parameter value: The NSDate value */ - internal func writeField(fieldName: String, value: NSDate?) { + internal func writeField(_ fieldName: String, value: Date?) { writeFieldName(fieldName) writeDate(value) } @@ -332,7 +332,7 @@ internal class JsonWriter { - Parameter fieldName: The name of the field - Parameter value: The Object/Array value - see function writeObject for more information. */ - internal func writeFieldWithObject(fieldName: String, value: AnyObject) throws { + internal func writeFieldWithObject(_ fieldName: String, value: Any) throws { writeFieldName(fieldName) try writeObject(value) } @@ -340,7 +340,7 @@ internal class JsonWriter { /** Writes a named arrays. */ - internal func writeArrayFieldStart(fieldName: String) { + internal func writeArrayFieldStart(_ fieldName: String) { writeFieldName(fieldName) writeStartArray() } @@ -348,7 +348,7 @@ internal class JsonWriter { /** Writes a named object. */ - internal func writeObjectFieldStart(fieldName: String) { + internal func writeObjectFieldStart(_ fieldName: String) { writeFieldName(fieldName) writeStartObject() } @@ -363,7 +363,7 @@ internal class JsonWriter { /** Writes the string to the outputstream. If the stream is not open the stream will be opened. */ - internal func write(theString: String) { + internal func write(_ theString: String) { if !outputStream.isOpen() { outputStream.open() } @@ -390,4 +390,4 @@ extension NSNumber { let numID = CFGetTypeID(self) return numID == boolID } -} \ No newline at end of file +} diff --git a/Pod/Classes/OuputStreams.swift b/Pod/Classes/OuputStreams.swift index d2906b9..cdb9cb7 100644 --- a/Pod/Classes/OuputStreams.swift +++ b/Pod/Classes/OuputStreams.swift @@ -15,11 +15,11 @@ import Foundation Buffer mechanisms. */ protocol OutputStream { - var outputStream: NSOutputStream { get } + var outputStream: Foundation.OutputStream { get } func open() func close() func isOpen() -> Bool - func write(theString: String) + func write(_ theString: String) func getDataAsString() -> String } @@ -28,17 +28,17 @@ protocol OutputStream { */ extension OutputStream { - private func write(buffer: UnsafePointer, maxLength len: Int) -> Int { + fileprivate func write(_ buffer: UnsafePointer, maxLength len: Int) -> Int { return self.outputStream.write(buffer, maxLength: len) } - private func stringToData(theString: String) -> NSData { - return theString.dataUsingEncoding(NSUTF8StringEncoding)! + fileprivate func stringToData(_ theString: String) -> Data { + return theString.data(using: String.Encoding.utf8)! } - func write(theString: String) { + func write(_ theString: String) { let data = stringToData(theString) - write(UnsafePointer(data.bytes), maxLength: data.length) + write((data as NSData).bytes.bindMemory(to: UInt8.self, capacity: data.count), maxLength: data.count) } func open(){ @@ -50,7 +50,7 @@ extension OutputStream { } func isOpen() -> Bool { - return outputStream.streamStatus == NSStreamStatus.Open + return outputStream.streamStatus == Stream.Status.open } } @@ -59,17 +59,17 @@ extension OutputStream { */ internal class MemOutputStream : OutputStream { - var outputStream: NSOutputStream + var outputStream: Foundation.OutputStream init(){ - self.outputStream = NSOutputStream.outputStreamToMemory() + self.outputStream = Foundation.OutputStream.toMemory() } func getDataAsString() -> String { close() - let data = outputStream.propertyForKey(NSStreamDataWrittenToMemoryStreamKey) + let data = outputStream.property(forKey: Stream.PropertyKey.dataWrittenToMemoryStreamKey) - return NSString(data: data as! NSData, encoding: NSUTF8StringEncoding) as! String + return NSString(data: data as! Data, encoding: String.Encoding.utf8.rawValue) as! String } } @@ -77,16 +77,16 @@ internal class MemOutputStream : OutputStream { A file output stream. The stream will overwrite any existing file content. */ internal class FileOutputStream : OutputStream { - var outputStream: NSOutputStream + var outputStream: Foundation.OutputStream var fileAtPath: String init(fileAtPath: String){ self.fileAtPath = fileAtPath - self.outputStream = NSOutputStream.init(toFileAtPath: fileAtPath, append: false)! + self.outputStream = Foundation.OutputStream.init(toFileAtPath: fileAtPath, append: false)! } func getDataAsString() -> String { close() - return try! NSString(contentsOfFile: fileAtPath, encoding: NSUTF8StringEncoding) as String + return try! NSString(contentsOfFile: fileAtPath, encoding: String.Encoding.utf8.rawValue) as String } -} \ No newline at end of file +} diff --git a/Pod/Classes/SampleCreator.swift b/Pod/Classes/SampleCreator.swift index 31c5cd9..aea9de5 100644 --- a/Pod/Classes/SampleCreator.swift +++ b/Pod/Classes/SampleCreator.swift @@ -17,7 +17,7 @@ class SampleCreatorRegistry { - Parameter typeName: the name of the type for what a SampleCreator is needed. - Returns: a SampleCreator for the type or nil if no SampleCreator exists for the type or the type is not supported. */ - static func get(typeName:String?) -> SampleCreator? { + static func get(_ typeName:String?) -> SampleCreator? { var sampleCreator:SampleCreator? = nil if let type = typeName { @@ -48,7 +48,7 @@ protocol SampleCreator { - Parameter sampleDict: the json dictionary containing a complete sample (inluding sub structures) - Returns: a HealthKit Sample that can be saved to the Health store or nil. */ - func createSample(sampleDict:AnyObject) -> HKSample? + func createSample(_ sampleDict:AnyObject) -> HKSample? } // abstract class implementation @@ -60,15 +60,15 @@ extension SampleCreator { - Parameter dict: The Json dictionary for a sample - Returns: a tupel with the start date and the end date */ - func dictToTimeframe(dict:Dictionary) -> (sDate:NSDate, eDate:NSDate) { + func dictToTimeframe(_ dict:Dictionary) -> (sDate:Date, eDate:Date) { let startDateNumber = dict[HealthKitConstants.S_DATE] as! Double let endDateOptNumber = dict[HealthKitConstants.E_DATE] as? Double - let startDate = NSDate(timeIntervalSince1970: startDateNumber/1000) - var endDate: NSDate? = nil + let startDate = Date(timeIntervalSince1970: startDateNumber/1000) + var endDate: Date? = nil if let endDateNumber = endDateOptNumber { - endDate = NSDate(timeIntervalSince1970: endDateNumber/1000) + endDate = Date(timeIntervalSince1970: endDateNumber/1000) } else { endDate = startDate } @@ -81,11 +81,11 @@ extension SampleCreator { - Parameter forType: the concrete category type that should be created - Returns: the CategorySample. Ready to save to the Health Store. */ - func dictToCategorySample(dict:Dictionary, forType type: HKCategoryType) -> HKCategorySample { + func dictToCategorySample(_ dict:Dictionary, forType type: HKCategoryType) -> HKCategorySample { let value = dict[HealthKitConstants.VALUE] as! Int let dates = dictToTimeframe(dict) - return HKCategorySample(type: type, value: value, startDate: dates.sDate , endDate: dates.eDate) + return HKCategorySample(type: type, value: value, start: dates.sDate , end: dates.eDate) } /** @@ -94,17 +94,17 @@ extension SampleCreator { - Parameter forType: the concrete quantity type that should be created - Returns: the QuantitySample. Ready to save to the Health Store. */ - func dictToQuantitySample(dict:Dictionary, forType type: HKQuantityType) -> HKQuantitySample { + func dictToQuantitySample(_ dict:Dictionary, forType type: HKQuantityType) -> HKQuantitySample { let dates = dictToTimeframe(dict) let value = dict[HealthKitConstants.VALUE] as! Double let strUnit = dict[HealthKitConstants.UNIT] as? String - let hkUnit = HKUnit(fromString: strUnit!) + let hkUnit = HKUnit(from: strUnit!) let quantity = HKQuantity(unit: hkUnit, doubleValue: value) - return HKQuantitySample(type: type, quantity: quantity, startDate: dates.sDate, endDate: dates.eDate) + return HKQuantitySample(type: type, quantity: quantity, start: dates.sDate, end: dates.eDate) } } @@ -113,10 +113,10 @@ class CategorySampleCreator : SampleCreator { let type: HKCategoryType init(typeName:String){ - self.type = HKObjectType.categoryTypeForIdentifier(typeName)! + self.type = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier(rawValue: typeName))! } - func createSample(sampleDict: AnyObject) -> HKSample? { + func createSample(_ sampleDict: AnyObject) -> HKSample? { if let dict = sampleDict as? Dictionary { return dictToCategorySample(dict, forType:type) } @@ -129,10 +129,10 @@ class QuantitySampleCreator : SampleCreator { let type: HKQuantityType init(typeName:String){ - self.type = HKObjectType.quantityTypeForIdentifier(typeName)! + self.type = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: typeName))! } - func createSample(sampleDict: AnyObject) -> HKSample? { + func createSample(_ sampleDict: AnyObject) -> HKSample? { if let dict = sampleDict as? Dictionary { return dictToQuantitySample(dict, forType:type) @@ -147,10 +147,10 @@ class CorrelationSampleCreator : SampleCreator { let type: HKCorrelationType init(typeName: String){ - self.type = HKObjectType.correlationTypeForIdentifier(typeName)! + self.type = HKObjectType.correlationType(forIdentifier: HKCorrelationTypeIdentifier(rawValue: typeName))! } - func createSample(sampleDict: AnyObject) -> HKSample? { + func createSample(_ sampleDict: AnyObject) -> HKSample? { if let dict = sampleDict as? Dictionary { let dates = dictToTimeframe(dict) @@ -162,7 +162,7 @@ class CorrelationSampleCreator : SampleCreator { if let subDict = object as? Dictionary { let subTypeName = subDict[HealthKitConstants.TYPE] as? String if let creator = SampleCreatorRegistry.get(subTypeName) { - let sampleOpt = creator.createSample(subDict) + let sampleOpt = creator.createSample(subDict as AnyObject) if let sample = sampleOpt { objects.insert(sample) } @@ -176,7 +176,7 @@ class CorrelationSampleCreator : SampleCreator { return nil } - return HKCorrelation(type: type, startDate: dates.sDate, endDate: dates.eDate, objects: objects) + return HKCorrelation(type: type, start: dates.sDate, end: dates.eDate, objects: objects) } return nil } @@ -186,7 +186,7 @@ class CorrelationSampleCreator : SampleCreator { class WorkoutSampleCreator : SampleCreator { let type = HKObjectType.workoutType() - func createSample(sampleDict: AnyObject) -> HKSample? { + func createSample(_ sampleDict: AnyObject) -> HKSample? { if let dict = sampleDict as? Dictionary { let dates = dictToTimeframe(dict) @@ -194,7 +194,7 @@ class WorkoutSampleCreator : SampleCreator { let activityTypeRawValue = dict[HealthKitConstants.WORKOUT_ACTIVITY_TYPE] as? UInt let activityType = HKWorkoutActivityType(rawValue: activityTypeRawValue!) - let duration = dict[HealthKitConstants.DURATION] as? NSTimeInterval + let duration = dict[HealthKitConstants.DURATION] as? TimeInterval let totalDistance = dict[HealthKitConstants.TOTAL_DISTANCE] as? Double // always HKUnit.meterUnit() let totalEnergyBurned = dict[HealthKitConstants.TOTAL_ENERGY_BURNED] as? Double //always HKUnit.kilocalorieUnit() @@ -206,15 +206,15 @@ class WorkoutSampleCreator : SampleCreator { let eventTypeRaw = subDict[HealthKitConstants.TYPE] as? Int let eventType = HKWorkoutEventType(rawValue: eventTypeRaw!)! let startDateNumber = subDict[HealthKitConstants.S_DATE] as! Double - let startDate = NSDate(timeIntervalSince1970: startDateNumber/1000) + let startDate = Date(timeIntervalSince1970: startDateNumber/1000) events.append(HKWorkoutEvent(type: eventType, date: startDate)) } } } if events.count > 0 { - return HKWorkout(activityType: activityType!, startDate: dates.sDate, endDate: dates.eDate, workoutEvents: events, totalEnergyBurned: HKQuantity(unit: HKUnit.kilocalorieUnit(), doubleValue: totalEnergyBurned!), totalDistance: HKQuantity(unit: HKUnit.meterUnit(), doubleValue: totalDistance!), metadata: nil) + return HKWorkout(activityType: activityType!, start: dates.sDate, end: dates.eDate, workoutEvents: events, totalEnergyBurned: HKQuantity(unit: HKUnit.kilocalorie(), doubleValue: totalEnergyBurned!), totalDistance: HKQuantity(unit: HKUnit.meter(), doubleValue: totalDistance!), metadata: nil) } else { - return HKWorkout(activityType: activityType!, startDate: dates.sDate, endDate: dates.eDate, duration: duration!, totalEnergyBurned: HKQuantity(unit: HKUnit.kilocalorieUnit(), doubleValue: totalEnergyBurned!), totalDistance: HKQuantity(unit: HKUnit.meterUnit(), doubleValue: totalDistance!), metadata: nil) + return HKWorkout(activityType: activityType!, start: dates.sDate, end: dates.eDate, duration: duration!, totalEnergyBurned: HKQuantity(unit: HKUnit.kilocalorie(), doubleValue: totalEnergyBurned!), totalDistance: HKQuantity(unit: HKUnit.meter(), doubleValue: totalDistance!), metadata: nil) } } return nil diff --git a/Pod/Classes/Util.swift b/Pod/Classes/Util.swift index a9c908e..c69a752 100644 --- a/Pod/Classes/Util.swift +++ b/Pod/Classes/Util.swift @@ -11,18 +11,18 @@ import Foundation /** Utility class for working with file names. */ -public class FileNameUtil { +open class FileNameUtil { /** removes the characters \ ? % * | . : , " < > form a string - Parameter userInput: a string that needs to be transformed to a filename - Returns: the string with all the characters mentioned above removed from the string. */ - public static func normalizeName(userInput: String) -> String { - let trimmedUserInput = userInput.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) + open static func normalizeName(_ userInput: String) -> String { + let trimmedUserInput = userInput.trimmingCharacters(in: CharacterSet.whitespaces) - let illegalFileNameCharacters = NSCharacterSet.init(charactersInString: "/\\?%*|.:, \"<>") + let illegalFileNameCharacters = CharacterSet.init(charactersIn: "/\\?%*|.:, \"<>") - return trimmedUserInput.componentsSeparatedByCharactersInSet(illegalFileNameCharacters).joinWithSeparator("") + return trimmedUserInput.components(separatedBy: illegalFileNameCharacters).joined(separator: "") } -} \ No newline at end of file +}