diff --git a/BluetoothKit.xcodeproj/project.pbxproj b/BluetoothKit.xcodeproj/project.pbxproj index 7a0032f..3cf83bf 100644 --- a/BluetoothKit.xcodeproj/project.pbxproj +++ b/BluetoothKit.xcodeproj/project.pbxproj @@ -287,7 +287,7 @@ attributes = { LastSwiftMigration = 0710; LastSwiftUpdateCheck = 0710; - LastUpgradeCheck = 0700; + LastUpgradeCheck = 0800; ORGANIZATIONNAME = "Rasmus Taulborg Hummelmose"; TargetAttributes = { C64CDDF21BE4C46A00F72549 = { @@ -295,6 +295,7 @@ }; C687E3971B8B496400B702D8 = { CreatedOnToolsVersion = 7.0; + LastSwiftMigration = 0800; }; C6ED86C01BA955A600C9B70B = { CreatedOnToolsVersion = 7.1; @@ -490,6 +491,7 @@ PRODUCT_BUNDLE_IDENTIFIER = com.rasmusth.BluetoothKit; SDKROOT = appletvos; SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = 3; TVOS_DEPLOYMENT_TARGET = 9.0; }; @@ -600,6 +602,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.rasmusth.BluetoothKit; SKIP_INSTALL = YES; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -615,6 +618,8 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.rasmusth.BluetoothKit; SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.0; }; name = Release; }; @@ -653,6 +658,7 @@ PRODUCT_BUNDLE_IDENTIFIER = com.rasmusth.BluetoothKit; SDKROOT = macosx; SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; }; diff --git a/BluetoothKit.xcodeproj/xcshareddata/xcschemes/BluetoothKit OSX.xcscheme b/BluetoothKit.xcodeproj/xcshareddata/xcschemes/BluetoothKit OSX.xcscheme index 909be00..9376e50 100644 --- a/BluetoothKit.xcodeproj/xcshareddata/xcschemes/BluetoothKit OSX.xcscheme +++ b/BluetoothKit.xcodeproj/xcshareddata/xcschemes/BluetoothKit OSX.xcscheme @@ -1,6 +1,6 @@ Bool { switch (lhs, rhs) { - case (.Available, .Available): return true - case (.Unavailable(cause: .Any), .Unavailable): return true - case (.Unavailable, .Unavailable(cause: .Any)): return true - case (.Unavailable(let lhsCause), .Unavailable(let rhsCause)): return lhsCause == rhsCause + case (.available, .available): return true + case (.unavailable(cause: .any), .unavailable): return true + case (.unavailable, .unavailable(cause: .any)): return true + case (.unavailable(let lhsCause), .unavailable(let rhsCause)): return lhsCause == rhsCause default: return false } } @@ -44,20 +44,22 @@ public func == (lhs: BKAvailability, rhs: BKAvailability) -> Bool { */ public enum BKAvailability: Equatable { - case Available - case Unavailable(cause: BKUnavailabilityCause) + case available + case unavailable(cause: BKUnavailabilityCause) - internal init(centralManagerState: CBCentralManagerState) { + @available(iOS 10.0, *) + internal init(centralManagerState: CBManagerState) { switch centralManagerState { - case .PoweredOn: self = .Available - default: self = .Unavailable(cause: BKUnavailabilityCause(centralManagerState: centralManagerState)) + case .poweredOn: self = .available + default: self = .unavailable(cause: BKUnavailabilityCause(centralManagerState: centralManagerState)) } } - internal init(peripheralManagerState: CBPeripheralManagerState) { + @available(iOS 10.0, *) + internal init(peripheralManagerState: CBManagerState) { switch peripheralManagerState { - case .PoweredOn: self = .Available - default: self = .Unavailable(cause: BKUnavailabilityCause(peripheralManagerState: peripheralManagerState)) + case .poweredOn: self = .available + default: self = .unavailable(cause: BKUnavailabilityCause(peripheralManagerState: peripheralManagerState)) } } @@ -73,32 +75,34 @@ public enum BKAvailability: Equatable { */ public enum BKUnavailabilityCause: NilLiteralConvertible { - case Any - case Resetting - case Unsupported - case Unauthorized - case PoweredOff + case any + case resetting + case unsupported + case unauthorized + case poweredOff public init(nilLiteral: Void) { - self = Any + self = any } - internal init(centralManagerState: CBCentralManagerState) { + @available(iOS 10.0, *) + internal init(centralManagerState: CBManagerState) { switch centralManagerState { - case .PoweredOff: self = PoweredOff - case .Resetting: self = Resetting - case .Unauthorized: self = Unauthorized - case .Unsupported: self = Unsupported + case .poweredOff: self = poweredOff + case .resetting: self = resetting + case .unauthorized: self = unauthorized + case .unsupported: self = unsupported default: self = nil } } - internal init(peripheralManagerState: CBPeripheralManagerState) { + @available(iOS 10.0, *) + internal init(peripheralManagerState: CBManagerState) { switch peripheralManagerState { - case .PoweredOff: self = PoweredOff - case .Resetting: self = Resetting - case .Unauthorized: self = Unauthorized - case .Unsupported: self = Unsupported + case .poweredOff: self = poweredOff + case .resetting: self = resetting + case .unauthorized: self = unauthorized + case .unsupported: self = unsupported default: self = nil } } @@ -110,8 +114,8 @@ public enum BKUnavailabilityCause: NilLiteralConvertible { */ public protocol BKAvailabilityObservable: class { var availabilityObservers: [BKWeakAvailabilityObserver] { get set } - func addAvailabilityObserver(availabilityObserver: BKAvailabilityObserver) - func removeAvailabilityObserver(availabilityObserver: BKAvailabilityObserver) + func addAvailabilityObserver(_ availabilityObserver: BKAvailabilityObserver) + func removeAvailabilityObserver(_ availabilityObserver: BKAvailabilityObserver) } /** @@ -130,7 +134,7 @@ public extension BKAvailabilityObservable { Add a new availability observer. The observer will be weakly stored. If the observer is already subscribed the call will be ignored. - parameter availabilityObserver: The availability observer to add. */ - func addAvailabilityObserver(availabilityObserver: BKAvailabilityObserver) { + func addAvailabilityObserver(_ availabilityObserver: BKAvailabilityObserver) { if !availabilityObservers.contains({ $0.availabilityObserver === availabilityObserver }) { availabilityObservers.append(BKWeakAvailabilityObserver(availabilityObserver: availabilityObserver)) } @@ -140,9 +144,9 @@ public extension BKAvailabilityObservable { Remove an availability observer. If the observer isn't subscribed the call will be ignored. - parameter availabilityObserver: The availability observer to remove. */ - func removeAvailabilityObserver(availabilityObserver: BKAvailabilityObserver) { + func removeAvailabilityObserver(_ availabilityObserver: BKAvailabilityObserver) { if availabilityObservers.contains({ $0.availabilityObserver === availabilityObserver }) { - availabilityObservers.removeAtIndex(availabilityObservers.indexOf({ $0 === availabilityObserver })!) + availabilityObservers.remove(at: availabilityObservers.index(where: { $0 === availabilityObserver })!) } } @@ -158,12 +162,12 @@ public protocol BKAvailabilityObserver: class { - parameter availabilityObservable: The object that registered the availability change. - parameter availability: The new availability value. */ - func availabilityObserver(availabilityObservable: BKAvailabilityObservable, availabilityDidChange availability: BKAvailability) + func availabilityObserver(_ availabilityObservable: BKAvailabilityObservable, availabilityDidChange availability: BKAvailability) /** Informs the observer that the cause of Bluetooth LE unavailability changed. - parameter availabilityObservable: The object that registered the cause change. - parameter unavailabilityCause: The new cause of unavailability. */ - func availabilityObserver(availabilityObservable: BKAvailabilityObservable, unavailabilityCauseDidChange unavailabilityCause: BKUnavailabilityCause) + func availabilityObserver(_ availabilityObservable: BKAvailabilityObservable, unavailabilityCauseDidChange unavailabilityCause: BKUnavailabilityCause) } diff --git a/Source/BKCBCentralManagerDelegateProxy.swift b/Source/BKCBCentralManagerDelegateProxy.swift index ebf1655..e3094fb 100644 --- a/Source/BKCBCentralManagerDelegateProxy.swift +++ b/Source/BKCBCentralManagerDelegateProxy.swift @@ -26,17 +26,17 @@ import Foundation import CoreBluetooth internal protocol BKCBCentralManagerStateDelegate: class { - func centralManagerDidUpdateState(central: CBCentralManager) + func centralManagerDidUpdateState(_ central: CBCentralManager) } internal protocol BKCBCentralManagerDiscoveryDelegate: class { - func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) + func centralManager(_ central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) } internal protocol BKCBCentralManagerConnectionDelegate: class { - func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) - func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) - func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) + func centralManager(_ central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) + func centralManager(_ central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) + func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) } internal class BKCBCentralManagerDelegateProxy: NSObject, CBCentralManagerDelegate { @@ -58,23 +58,23 @@ internal class BKCBCentralManagerDelegateProxy: NSObject, CBCentralManagerDelega // MARK: CBCentralManagerDelegate - internal func centralManagerDidUpdateState(central: CBCentralManager) { + internal func centralManagerDidUpdateState(_ central: CBCentralManager) { stateDelegate?.centralManagerDidUpdateState(central) } - internal func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) { + internal func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : AnyObject], rssi RSSI: NSNumber) { discoveryDelegate?.centralManager(central, didDiscoverPeripheral: peripheral, advertisementData: advertisementData, RSSI: RSSI) } - internal func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) { + internal func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { connectionDelegate?.centralManager(central, didConnectPeripheral: peripheral) } - internal func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) { + internal func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: NSError?) { connectionDelegate?.centralManager(central, didFailToConnectPeripheral: peripheral, error: error) } - internal func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) { + internal func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) { connectionDelegate?.centralManager(central, didDisconnectPeripheral: peripheral, error: error) } } diff --git a/Source/BKCBPeripheralDelegateProxy.swift b/Source/BKCBPeripheralDelegateProxy.swift index 45bc4a9..9f7edb3 100644 --- a/Source/BKCBPeripheralDelegateProxy.swift +++ b/Source/BKCBPeripheralDelegateProxy.swift @@ -26,10 +26,10 @@ import Foundation import CoreBluetooth internal protocol BKCBPeripheralDelegate: class { - func peripheralDidUpdateName(peripheral: CBPeripheral) - func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) - func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) - func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) + func peripheralDidUpdateName(_ peripheral: CBPeripheral) + func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: NSError?) + func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) + func peripheral(_ peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) } internal class BKCBPeripheralDelegateProxy: NSObject, CBPeripheralDelegate { @@ -46,59 +46,59 @@ internal class BKCBPeripheralDelegateProxy: NSObject, CBPeripheralDelegate { // MARK: CBPeripheralDelegate - internal func peripheralDidUpdateName(peripheral: CBPeripheral) { + internal func peripheralDidUpdateName(_ peripheral: CBPeripheral) { // print("peripheralDidUpdateName: \(peripheral)") delegate?.peripheralDidUpdateName(peripheral) } - internal func peripheral(peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) { + internal func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) { // print("peripheral: \(peripheral) didModifyServices invalidatedServices: \(invalidatedServices)") } - internal func peripheralDidUpdateRSSI(peripheral: CBPeripheral, error: NSError?) { + internal func peripheralDidUpdateRSSI(_ peripheral: CBPeripheral, error: NSError?) { // print("peripheralDidUpdateRSSI: \(peripheral), error: \(error)") } - internal func peripheral(peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: NSError?) { + internal func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: NSError?) { // print("peripheral: \(peripheral) didReadRSSI: \(RSSI), error: \(error)") } - internal func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) { + internal func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: NSError?) { // print("peripheral: \(peripheral) didDiscoverServices error: \(error)") delegate?.peripheral(peripheral, didDiscoverServices: error) } - internal func peripheral(peripheral: CBPeripheral, didDiscoverIncludedServicesForService service: CBService, error: NSError?) { + internal func peripheral(_ peripheral: CBPeripheral, didDiscoverIncludedServicesFor service: CBService, error: NSError?) { // print("peripheral: \(peripheral) didDiscoverIncludedServicesForService: \(service), error: \(error)") } - internal func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) { + internal func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: NSError?) { // print("peripheral: \(peripheral) didDiscoverCharacteristicsForService: \(service), error: \(error)") delegate?.peripheral(peripheral, didDiscoverCharacteristicsForService: service, error: error) } - internal func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) { + internal func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: NSError?) { // print("peripheral: \(peripheral) didUpdateValueForCharacteristic: \(characteristic), error: \(error)") delegate?.peripheral(peripheral, didUpdateValueForCharacteristic: characteristic, error: error) } - internal func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) { + internal func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: NSError?) { // print("peripheral: \(peripheral), didWriteValueForCharacteristic: \(characteristic), error: \(error)") } - internal func peripheral(peripheral: CBPeripheral, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic, error: NSError?) { + internal func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: NSError?) { // print("peripheral: \(peripheral) didUpdateNotificationStateForCharacteristic: \(characteristic), error: \(error)") } - internal func peripheral(peripheral: CBPeripheral, didDiscoverDescriptorsForCharacteristic characteristic: CBCharacteristic, error: NSError?) { + internal func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: NSError?) { // print("peripheral: \(peripheral) didDiscoverDescriptorsForCharacteristic: \(characteristic), error: \(error)") } - internal func peripheral(peripheral: CBPeripheral, didUpdateValueForDescriptor descriptor: CBDescriptor, error: NSError?) { + internal func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: NSError?) { // print("peripheral: \(peripheral) didUpdateValueForDescriptor: \(descriptor), error: \(error)") } - internal func peripheral(peripheral: CBPeripheral, didWriteValueForDescriptor descriptor: CBDescriptor, error: NSError?) { + internal func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: NSError?) { // print("peripheral: \(peripheral) didWriteValueForDescriptor: \(descriptor), error: \(error)") } diff --git a/Source/BKCBPeripheralManagerDelegateProxy.swift b/Source/BKCBPeripheralManagerDelegateProxy.swift index 297ba45..bc1b7ae 100644 --- a/Source/BKCBPeripheralManagerDelegateProxy.swift +++ b/Source/BKCBPeripheralManagerDelegateProxy.swift @@ -26,13 +26,13 @@ import Foundation import CoreBluetooth internal protocol BKCBPeripheralManagerDelegate: class { - func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) - func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager, error: NSError?) - func peripheralManager(peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) - func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didSubscribeToCharacteristic characteristic: CBCharacteristic) - func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFromCharacteristic characteristic: CBCharacteristic) - func peripheralManager(peripheral: CBPeripheralManager, didReceiveWriteRequests requests: [CBATTRequest]) - func peripheralManagerIsReadyToUpdateSubscribers(peripheral: CBPeripheralManager) + func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) + func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: NSError?) + func peripheralManager(_ peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) + func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeToCharacteristic characteristic: CBCharacteristic) + func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFromCharacteristic characteristic: CBCharacteristic) + func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWriteRequests requests: [CBATTRequest]) + func peripheralManagerIsReadyToUpdateSubscribers(_ peripheral: CBPeripheralManager) } internal class BKCBPeripheralManagerDelegateProxy: NSObject, CBPeripheralManagerDelegate { @@ -49,45 +49,45 @@ internal class BKCBPeripheralManagerDelegateProxy: NSObject, CBPeripheralManager // MARK: CBPeripheralManagerDelegate - internal func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) { + internal func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { // print("peripheralManagerDidUpdateState: \(peripheral)") delegate?.peripheralManagerDidUpdateState(peripheral) } - internal func peripheralManager(peripheral: CBPeripheralManager, willRestoreState dict: [String : AnyObject]) { + internal func peripheralManager(_ peripheral: CBPeripheralManager, willRestoreState dict: [String : AnyObject]) { // print("peripheralManager: \(peripheral) willRestoreState: \(dict)") } - internal func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager, error: NSError?) { + internal func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: NSError?) { // print("peripheralManagerDidStartAdvertising: \(peripheral) error: \(error)") delegate?.peripheralManagerDidStartAdvertising(peripheral, error: error) } - internal func peripheralManager(peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) { + internal func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: NSError?) { // print("peripheralManager: \(peripheral) didAddService: \(service) error: \(error)") delegate?.peripheralManager(peripheral, didAddService: service, error: error) } - internal func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didSubscribeToCharacteristic characteristic: CBCharacteristic) { + internal func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) { // print("peripheralManager: \(peripheral) central: \(central) didSubscribeToCharacteristic: \(characteristic)") delegate?.peripheralManager(peripheral, central: central, didSubscribeToCharacteristic: characteristic) } - internal func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFromCharacteristic characteristic: CBCharacteristic) { + internal func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) { // print("peripheralManager: \(peripheral) central: \(central) didUnsubscribeFromCharacteristic: \(characteristic)") delegate?.peripheralManager(peripheral, central: central, didUnsubscribeFromCharacteristic: characteristic) } - internal func peripheralManager(peripheral: CBPeripheralManager, didReceiveReadRequest request: CBATTRequest) { + internal func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) { // print("peripheralManager: \(peripheral) didReceiveReadRequest: \(request)") } - internal func peripheralManager(peripheral: CBPeripheralManager, didReceiveWriteRequests requests: [CBATTRequest]) { + internal func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) { // print("peripheralManager: \(peripheral) didReceiveWriteRequests: \(requests)") delegate?.peripheralManager(peripheral, didReceiveWriteRequests: requests) } - internal func peripheralManagerIsReadyToUpdateSubscribers(peripheral: CBPeripheralManager) { + internal func peripheralManagerIsReady(toUpdateSubscribers peripheral: CBPeripheralManager) { // print("peripheralManagerIsReadyToUpdateSubscribers: \(peripheral)") delegate?.peripheralManagerIsReadyToUpdateSubscribers(peripheral) } diff --git a/Source/BKCentral.swift b/Source/BKCentral.swift index 23fd9d3..955052f 100644 --- a/Source/BKCentral.swift +++ b/Source/BKCentral.swift @@ -34,13 +34,15 @@ public protocol BKCentralDelegate: class { - parameter central: The central from which it disconnected. - parameter remotePeripheral: The remote peripheral that disconnected. */ - func central(central: BKCentral, remotePeripheralDidDisconnect remotePeripheral: BKRemotePeripheral) + @available(iOS 10.0, *) + func central(_ central: BKCentral, remotePeripheralDidDisconnect remotePeripheral: BKRemotePeripheral) } /** The class used to take the Bluetooth LE central role. The central discovers remote peripherals by scanning and connects to them. When a connection is established the central can receive data from the remote peripheral. */ +@available(iOS 10.0, *) public class BKCentral: BKPeer, BKCBCentralManagerStateDelegate, BKConnectionPoolDelegate, BKAvailabilityObservable { // MARK: Type Aliases @@ -61,14 +63,15 @@ public class BKCentral: BKPeer, BKCBCentralManagerStateDelegate, BKConnectionPoo - Waiting: The scan is on hold due while waiting for the in-between delay to expire, after which it will start again. */ public enum ContinuousScanState { - case Stopped - case Scanning - case Waiting + case stopped + case scanning + case waiting } // MARK: Properties /// Bluetooth LE availability, derived from the underlying CBCentralManager. + @available(iOS 10.0, *) public var availability: BKAvailability? { if let centralManager = _centralManager { return BKAvailability(centralManagerState: centralManager.state) @@ -135,16 +138,16 @@ public class BKCentral: BKPeer, BKCBCentralManagerStateDelegate, BKConnectionPoo - parameter configuration: The configuration defining which UUIDs to use when discovering peripherals. - throws: Throws an InternalError if the BKCentral object is already started. */ - public func startWithConfiguration(configuration: BKConfiguration) throws { + public func startWithConfiguration(_ configuration: BKConfiguration) throws { do { - try stateMachine.handleEvent(.Start) + try stateMachine.handleEvent(.start) _configuration = configuration _centralManager = CBCentralManager(delegate: centralManagerDelegate, queue: nil, options: nil) scanner.configuration = configuration scanner.centralManager = centralManager connectionPool.centralManager = centralManager } catch let error { - throw BKError.InternalError(underlyingError: error) + throw BKError.internalError(underlyingError: error) } } @@ -154,20 +157,20 @@ public class BKCentral: BKPeer, BKCBCentralManagerStateDelegate, BKConnectionPoo - parameter progressHandler: A progress handler allowing you to react immediately when a peripheral is discovered during a scan. - parameter completionHandler: A completion handler allowing you to react on the full result of discovered peripherals or an error if one occured. */ - public func scanWithDuration(duration: NSTimeInterval = 3, progressHandler: ScanProgressHandler?, completionHandler: ScanCompletionHandler?) { + public func scanWithDuration(_ duration: TimeInterval = 3, progressHandler: ScanProgressHandler?, completionHandler: ScanCompletionHandler?) { do { - try stateMachine.handleEvent(.Scan) + try stateMachine.handleEvent(.scan) try scanner.scanWithDuration(duration, progressHandler: progressHandler) { result, error in var returnError: BKError? if error == nil { - _ = try? self.stateMachine.handleEvent(.SetAvailable) + _ = try? self.stateMachine.handleEvent(.setAvailable) } else { - returnError = .InternalError(underlyingError: error) + returnError = .internalError(underlyingError: error) } completionHandler?(result: result, error: returnError) } } catch let error { - completionHandler?(result: nil, error: .InternalError(underlyingError: error)) + completionHandler?(result: nil, error: .internalError(underlyingError: error)) return } } @@ -180,19 +183,20 @@ public class BKCentral: BKPeer, BKCBCentralManagerStateDelegate, BKConnectionPoo - parameter inBetweenDelay: The number of seconds to wait for, in-between scans (defaults to 3). - parameter errorHandler: An error handler allowing you to react when an error occurs. For now this is also called when the scan is manually interrupted. */ - public func scanContinuouslyWithChangeHandler(changeHandler: ContinuousScanChangeHandler, stateHandler: ContinuousScanStateHandler?, duration: NSTimeInterval = 3, inBetweenDelay: NSTimeInterval = 3, errorHandler: ContinuousScanErrorHandler?) { + @available(iOS 10.0, *) + public func scanContinuouslyWithChangeHandler(_ changeHandler: ContinuousScanChangeHandler, stateHandler: ContinuousScanStateHandler?, duration: TimeInterval = 3, inBetweenDelay: TimeInterval = 3, errorHandler: ContinuousScanErrorHandler?) { do { - try stateMachine.handleEvent(.Scan) + try stateMachine.handleEvent(.scan) continuousScanner.scanContinuouslyWithChangeHandler(changeHandler, stateHandler: { newState in - if newState == .Stopped && self.availability == .Available { - _ = try? self.stateMachine.handleEvent(.SetAvailable) + if newState == .stopped && self.availability == .available { + _ = try? self.stateMachine.handleEvent(.setAvailable) } stateHandler?(newState: newState) }, duration: duration, inBetweenDelay: inBetweenDelay, errorHandler: { error in - errorHandler?(error: .InternalError(underlyingError: error)) + errorHandler?(error: .internalError(underlyingError: error)) }) } catch let error { - errorHandler?(error: .InternalError(underlyingError: error)) + errorHandler?(error: .internalError(underlyingError: error)) } } @@ -210,20 +214,20 @@ public class BKCentral: BKPeer, BKCBCentralManagerStateDelegate, BKConnectionPoo - parameter remotePeripheral: The remote peripheral to connect to. - parameter completionHandler: A completion handler allowing you to react when the connection attempt succeeded or failed. */ - public func connect(timeout: NSTimeInterval = 3, remotePeripheral: BKRemotePeripheral, completionHandler: ConnectCompletionHandler) { + public func connect(_ timeout: TimeInterval = 3, remotePeripheral: BKRemotePeripheral, completionHandler: ConnectCompletionHandler) { do { - try stateMachine.handleEvent(.Connect) + try stateMachine.handleEvent(.connect) try connectionPool.connectWithTimeout(timeout, remotePeripheral: remotePeripheral) { remotePeripheral, error in var returnError: BKError? if error == nil { - _ = try? self.stateMachine.handleEvent(.SetAvailable) + _ = try? self.stateMachine.handleEvent(.setAvailable) } else { - returnError = .InternalError(underlyingError: error) + returnError = .internalError(underlyingError: error) } completionHandler(remotePeripheral: remotePeripheral, error: returnError) } } catch let error { - completionHandler(remotePeripheral: remotePeripheral, error: .InternalError(underlyingError: error)) + completionHandler(remotePeripheral: remotePeripheral, error: .internalError(underlyingError: error)) return } } @@ -233,11 +237,11 @@ public class BKCentral: BKPeer, BKCBCentralManagerStateDelegate, BKConnectionPoo - parameter remotePeripheral: The peripheral to disconnect. - throws: Throws an InternalError if the remote peripheral is not currently connected. */ - public func disconnectRemotePeripheral(remotePeripheral: BKRemotePeripheral) throws { + public func disconnectRemotePeripheral(_ remotePeripheral: BKRemotePeripheral) throws { do { try connectionPool.disconnectRemotePeripheral(remotePeripheral) } catch let error { - throw BKError.InternalError(underlyingError: error) + throw BKError.internalError(underlyingError: error) } } @@ -247,24 +251,24 @@ public class BKCentral: BKPeer, BKCBCentralManagerStateDelegate, BKConnectionPoo */ public func stop() throws { do { - try stateMachine.handleEvent(.Stop) + try stateMachine.handleEvent(.stop) interruptScan() connectionPool.reset() _configuration = nil _centralManager = nil } catch let error { - throw BKError.InternalError(underlyingError: error) + throw BKError.internalError(underlyingError: error) } } // MARK: Internal Functions - internal func setUnavailable(cause: BKUnavailabilityCause, oldCause: BKUnavailabilityCause?) { + internal func setUnavailable(_ cause: BKUnavailabilityCause, oldCause: BKUnavailabilityCause?) { scanner.interruptScan() connectionPool.reset() if oldCause == nil { for availabilityObserver in availabilityObservers { - availabilityObserver.availabilityObserver?.availabilityObserver(self, availabilityDidChange: .Unavailable(cause: cause)) + availabilityObserver.availabilityObserver?.availabilityObserver(self, availabilityDidChange: .unavailable(cause: cause)) } } else if oldCause != nil && oldCause != cause { for availabilityObserver in availabilityObservers { @@ -273,39 +277,40 @@ public class BKCentral: BKPeer, BKCBCentralManagerStateDelegate, BKConnectionPoo } } - internal override func sendData(data: NSData, toRemotePeer remotePeer: BKRemotePeer) -> Bool { + internal override func sendData(_ data: Data, toRemotePeer remotePeer: BKRemotePeer) -> Bool { guard let remotePeripheral = remotePeer as? BKRemotePeripheral, peripheral = remotePeripheral.peripheral, characteristic = remotePeripheral.characteristicData else { return false } - peripheral.writeValue(data, forCharacteristic: characteristic, type: .WithoutResponse) + peripheral.writeValue(data, for: characteristic, type: .withoutResponse) return true } // MARK: BKCBCentralManagerStateDelegate - internal func centralManagerDidUpdateState(central: CBCentralManager) { + + internal func centralManagerDidUpdateState(_ central: CBCentralManager) { switch central.state { - case .Unknown, .Resetting: + case .unknown, .resetting: break - case .Unsupported, .Unauthorized, .PoweredOff: + case .unsupported, .unauthorized, .poweredOff: let newCause = BKUnavailabilityCause(centralManagerState: central.state) switch stateMachine.state { - case let .Unavailable(cause): + case let .unavailable(cause): let oldCause = cause - _ = try? stateMachine.handleEvent(.SetUnavailable(cause: newCause)) + _ = try? stateMachine.handleEvent(.setUnavailable(cause: newCause)) setUnavailable(oldCause, oldCause: newCause) default: - _ = try? stateMachine.handleEvent(.SetUnavailable(cause: newCause)) + _ = try? stateMachine.handleEvent(.setUnavailable(cause: newCause)) setUnavailable(newCause, oldCause: nil) } - case .PoweredOn: + case .poweredOn: let state = stateMachine.state - _ = try? stateMachine.handleEvent(.SetAvailable) + _ = try? stateMachine.handleEvent(.setAvailable) switch state { - case .Starting, .Unavailable: + case .starting, .unavailable: for availabilityObserver in availabilityObservers { - availabilityObserver.availabilityObserver?.availabilityObserver(self, availabilityDidChange: .Available) + availabilityObserver.availabilityObserver?.availabilityObserver(self, availabilityDidChange: .available) } default: break @@ -315,7 +320,7 @@ public class BKCentral: BKPeer, BKCBCentralManagerStateDelegate, BKConnectionPoo // MARK: BKConnectionPoolDelegate - internal func connectionPool(connectionPool: BKConnectionPool, remotePeripheralDidDisconnect remotePeripheral: BKRemotePeripheral) { + internal func connectionPool(_ connectionPool: BKConnectionPool, remotePeripheralDidDisconnect remotePeripheral: BKRemotePeripheral) { delegate?.central(self, remotePeripheralDidDisconnect: remotePeripheral) } diff --git a/Source/BKCentralStateMachine.swift b/Source/BKCentralStateMachine.swift index 7019b18..0fae222 100644 --- a/Source/BKCentralStateMachine.swift +++ b/Source/BKCentralStateMachine.swift @@ -28,16 +28,16 @@ internal class BKCentralStateMachine { // MARK: Enums - internal enum Error: ErrorType { - case Transitioning(currentState: State, validStates: [State]) + internal enum Error: ErrorProtocol { + case transitioning(currentState: State, validStates: [State]) } internal enum State { - case Initialized, Starting, Unavailable(cause: BKUnavailabilityCause), Available, Scanning + case initialized, starting, unavailable(cause: BKUnavailabilityCause), available, scanning } internal enum Event { - case Start, SetUnavailable(cause: BKUnavailabilityCause), SetAvailable, Scan, Connect, Stop + case start, setUnavailable(cause: BKUnavailabilityCause), setAvailable, scan, connect, stop } // MARK: Properties @@ -47,79 +47,79 @@ internal class BKCentralStateMachine { // MARK: Initialization internal init() { - self.state = .Initialized + self.state = .initialized } // MARK: Functions - internal func handleEvent(event: Event) throws { + internal func handleEvent(_ event: Event) throws { switch event { - case .Start: + case .start: try handleStartEvent(event) - case .SetAvailable: + case .setAvailable: try handleSetAvailableEvent(event) - case let .SetUnavailable(newCause): + case let .setUnavailable(newCause): try handleSetUnavailableEvent(event, cause: newCause) - case .Scan: + case .scan: try handleScanEvent(event) - case .Connect: + case .connect: try handleConnectEvent(event) - case .Stop: + case .stop: try handleStopEvent(event) } } - private func handleStartEvent(event: Event) throws { + private func handleStartEvent(_ event: Event) throws { switch state { - case .Initialized: - state = .Starting + case .initialized: + state = .starting default: - throw Error.Transitioning(currentState: state, validStates: [ .Initialized ]) + throw Error.transitioning(currentState: state, validStates: [ .initialized ]) } } - private func handleSetAvailableEvent(event: Event) throws { + private func handleSetAvailableEvent(_ event: Event) throws { switch state { - case .Initialized: - throw Error.Transitioning(currentState: state, validStates: [ .Starting, .Available, .Unavailable(cause: nil) ]) + case .initialized: + throw Error.transitioning(currentState: state, validStates: [ .starting, .available, .unavailable(cause: nil) ]) default: - state = .Available + state = .available } } - private func handleSetUnavailableEvent(event: Event, cause: BKUnavailabilityCause) throws { + private func handleSetUnavailableEvent(_ event: Event, cause: BKUnavailabilityCause) throws { switch state { - case .Initialized: - throw Error.Transitioning(currentState: state, validStates: [ .Starting, .Available, .Unavailable(cause: nil) ]) + case .initialized: + throw Error.transitioning(currentState: state, validStates: [ .starting, .available, .unavailable(cause: nil) ]) default: - state = .Unavailable(cause: cause) + state = .unavailable(cause: cause) } } - private func handleScanEvent(event: Event) throws { + private func handleScanEvent(_ event: Event) throws { switch state { - case .Available: - state = .Scanning + case .available: + state = .scanning default: - throw Error.Transitioning(currentState: state, validStates: [ .Available ]) + throw Error.transitioning(currentState: state, validStates: [ .available ]) } } - private func handleConnectEvent(event: Event) throws { + private func handleConnectEvent(_ event: Event) throws { switch state { - case .Available, .Scanning: + case .available, .scanning: break default: - throw Error.Transitioning(currentState: state, validStates: [ .Available, .Scanning ]) + throw Error.transitioning(currentState: state, validStates: [ .available, .scanning ]) } } - private func handleStopEvent(event: Event) throws { + private func handleStopEvent(_ event: Event) throws { switch state { - case .Initialized: - throw Error.Transitioning(currentState: state, validStates: [ .Starting, .Unavailable(cause: nil), .Available, .Scanning ]) + case .initialized: + throw Error.transitioning(currentState: state, validStates: [ .starting, .unavailable(cause: nil), .available, .scanning ]) default: - state = .Initialized + state = .initialized } } diff --git a/Source/BKConfiguration.swift b/Source/BKConfiguration.swift index 4bec1f8..ad28f0b 100644 --- a/Source/BKConfiguration.swift +++ b/Source/BKConfiguration.swift @@ -39,10 +39,10 @@ public class BKConfiguration { public var dataServiceCharacteristicUUID: CBUUID /// Data used to indicate that no more data is coming when communicating. - public var endOfDataMark: NSData + public var endOfDataMark: Data /// Data used to indicate that a transfer was cancellen when communicating. - public var dataCancelledMark: NSData + public var dataCancelledMark: Data internal var serviceUUIDs: [CBUUID] { let serviceUUIDs = [ dataServiceUUID ] @@ -51,16 +51,16 @@ public class BKConfiguration { // MARK: Initialization - public init(dataServiceUUID: NSUUID, dataServiceCharacteristicUUID: NSUUID) { - self.dataServiceUUID = CBUUID(NSUUID: dataServiceUUID) - self.dataServiceCharacteristicUUID = CBUUID(NSUUID: dataServiceCharacteristicUUID) - endOfDataMark = "EOD".dataUsingEncoding(NSUTF8StringEncoding)! - dataCancelledMark = "COD".dataUsingEncoding(NSUTF8StringEncoding)! + public init(dataServiceUUID: UUID, dataServiceCharacteristicUUID: UUID) { + self.dataServiceUUID = CBUUID(nsuuid: dataServiceUUID) + self.dataServiceCharacteristicUUID = CBUUID(nsuuid: dataServiceCharacteristicUUID) + endOfDataMark = "EOD".data(using: String.Encoding.utf8)! + dataCancelledMark = "COD".data(using: String.Encoding.utf8)! } // MARK Functions - internal func characteristicUUIDsForServiceUUID(serviceUUID: CBUUID) -> [CBUUID] { + internal func characteristicUUIDsForServiceUUID(_ serviceUUID: CBUUID) -> [CBUUID] { if serviceUUID == dataServiceUUID { return [ dataServiceCharacteristicUUID ] } diff --git a/Source/BKConnectionAttempt.swift b/Source/BKConnectionAttempt.swift index 9dec124..efedd3c 100644 --- a/Source/BKConnectionAttempt.swift +++ b/Source/BKConnectionAttempt.swift @@ -25,20 +25,20 @@ import Foundation internal func == (lhs: BKConnectionAttempt, rhs: BKConnectionAttempt) -> Bool { - return lhs.remotePeripheral.identifier.isEqual(rhs.remotePeripheral.identifier) + return (lhs.remotePeripheral.identifier == rhs.remotePeripheral.identifier) } internal class BKConnectionAttempt: Equatable { // MARK: Properties - internal let timer: NSTimer + internal let timer: Timer internal let remotePeripheral: BKRemotePeripheral internal let completionHandler: ((peripheralEntity: BKRemotePeripheral, error: BKConnectionPool.Error?) -> Void) // MARK: Initialization - internal init(remotePeripheral: BKRemotePeripheral, timer: NSTimer, completionHandler: ((peripheralEntity: BKRemotePeripheral, error: BKConnectionPool.Error?) -> Void)) { + internal init(remotePeripheral: BKRemotePeripheral, timer: Timer, completionHandler: ((peripheralEntity: BKRemotePeripheral, error: BKConnectionPool.Error?) -> Void)) { self.remotePeripheral = remotePeripheral self.timer = timer self.completionHandler = completionHandler diff --git a/Source/BKConnectionPool.swift b/Source/BKConnectionPool.swift index 08c5b4a..5be0e18 100644 --- a/Source/BKConnectionPool.swift +++ b/Source/BKConnectionPool.swift @@ -26,23 +26,23 @@ import Foundation import CoreBluetooth internal protocol BKConnectionPoolDelegate: class { - func connectionPool(connectionPool: BKConnectionPool, remotePeripheralDidDisconnect remotePeripheral: BKRemotePeripheral) + func connectionPool(_ connectionPool: BKConnectionPool, remotePeripheralDidDisconnect remotePeripheral: BKRemotePeripheral) } internal class BKConnectionPool: BKCBCentralManagerConnectionDelegate { // MARK: Enums - internal enum Error: ErrorType { - case NoCentralManagerSet - case AlreadyConnected - case AlreadyConnecting - case ConnectionByUUIDIsNotImplementedYet - case Interrupted - case NoConnectionAttemptForRemotePeripheral - case NoConnectionForRemotePeripheral - case TimeoutElapsed - case Internal(underlyingError: ErrorType?) + internal enum Error: ErrorProtocol { + case noCentralManagerSet + case alreadyConnected + case alreadyConnecting + case connectionByUUIDIsNotImplementedYet + case interrupted + case noConnectionAttemptForRemotePeripheral + case noConnectionForRemotePeripheral + case timeoutElapsed + case `internal`(underlyingError: ErrorProtocol?) } // MARK: Properties @@ -54,37 +54,37 @@ internal class BKConnectionPool: BKCBCentralManagerConnectionDelegate { // MARK: Internal Functions - internal func connectWithTimeout(timeout: NSTimeInterval, remotePeripheral: BKRemotePeripheral, completionHandler: ((peripheralEntity: BKRemotePeripheral, error: Error?) -> Void)) throws { + internal func connectWithTimeout(_ timeout: TimeInterval, remotePeripheral: BKRemotePeripheral, completionHandler: ((peripheralEntity: BKRemotePeripheral, error: Error?) -> Void)) throws { guard centralManager != nil else { - throw Error.NoCentralManagerSet + throw Error.noCentralManagerSet } guard !connectedRemotePeripherals.contains(remotePeripheral) else { - throw Error.AlreadyConnected + throw Error.alreadyConnected } guard !connectionAttempts.map({ connectionAttempt in return connectionAttempt.remotePeripheral }).contains(remotePeripheral) else { - throw Error.AlreadyConnecting + throw Error.alreadyConnecting } guard remotePeripheral.peripheral != nil else { - throw Error.ConnectionByUUIDIsNotImplementedYet + throw Error.connectionByUUIDIsNotImplementedYet } - let timer = NSTimer.scheduledTimerWithTimeInterval(timeout, target: self, selector: #selector(BKConnectionPool.timerElapsed(_:)), userInfo: nil, repeats: false) + let timer = Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(BKConnectionPool.timerElapsed(_:)), userInfo: nil, repeats: false) remotePeripheral.prepareForConnection() connectionAttempts.append(BKConnectionAttempt(remotePeripheral: remotePeripheral, timer: timer, completionHandler: completionHandler)) - centralManager!.connectPeripheral(remotePeripheral.peripheral!, options: nil) + centralManager!.connect(remotePeripheral.peripheral!, options: nil) } - internal func interruptConnectionAttemptForRemotePeripheral(remotePeripheral: BKRemotePeripheral) throws { + internal func interruptConnectionAttemptForRemotePeripheral(_ remotePeripheral: BKRemotePeripheral) throws { let connectionAttempt = connectionAttemptForRemotePeripheral(remotePeripheral) guard connectionAttempt != nil else { - throw Error.NoConnectionAttemptForRemotePeripheral + throw Error.noConnectionAttemptForRemotePeripheral } - failConnectionAttempt(connectionAttempt!, error: .Interrupted) + failConnectionAttempt(connectionAttempt!, error: .interrupted) } - internal func disconnectRemotePeripheral(remotePeripheral: BKRemotePeripheral) throws { + internal func disconnectRemotePeripheral(_ remotePeripheral: BKRemotePeripheral) throws { let connectedRemotePeripheral = connectedRemotePeripherals.filter({ $0 == remotePeripheral }).last guard connectedRemotePeripheral != nil else { - throw Error.NoConnectionForRemotePeripheral + throw Error.noConnectionForRemotePeripheral } connectedRemotePeripheral?.unsubscribe() centralManager.cancelPeripheralConnection(connectedRemotePeripheral!.peripheral!) @@ -92,7 +92,7 @@ internal class BKConnectionPool: BKCBCentralManagerConnectionDelegate { internal func reset() { for connectionAttempt in connectionAttempts { - failConnectionAttempt(connectionAttempt, error: .Interrupted) + failConnectionAttempt(connectionAttempt, error: .interrupted) } connectionAttempts.removeAll() for remotePeripheral in connectedRemotePeripherals { @@ -103,24 +103,24 @@ internal class BKConnectionPool: BKCBCentralManagerConnectionDelegate { // MARK: Private Functions - private func connectionAttemptForRemotePeripheral(remotePeripheral: BKRemotePeripheral) -> BKConnectionAttempt? { + private func connectionAttemptForRemotePeripheral(_ remotePeripheral: BKRemotePeripheral) -> BKConnectionAttempt? { return connectionAttempts.filter({ $0.remotePeripheral == remotePeripheral }).last } - private func connectionAttemptForTimer(timer: NSTimer) -> BKConnectionAttempt? { + private func connectionAttemptForTimer(_ timer: Timer) -> BKConnectionAttempt? { return connectionAttempts.filter({ $0.timer == timer }).last } - private func connectionAttemptForPeripheral(peripheral: CBPeripheral) -> BKConnectionAttempt? { + private func connectionAttemptForPeripheral(_ peripheral: CBPeripheral) -> BKConnectionAttempt? { return connectionAttempts.filter({ $0.remotePeripheral.peripheral == peripheral }).last } - @objc private func timerElapsed(timer: NSTimer) { - failConnectionAttempt(connectionAttemptForTimer(timer)!, error: .TimeoutElapsed) + @objc private func timerElapsed(_ timer: Timer) { + failConnectionAttempt(connectionAttemptForTimer(timer)!, error: .timeoutElapsed) } - private func failConnectionAttempt(connectionAttempt: BKConnectionAttempt, error: Error) { - connectionAttempts.removeAtIndex(connectionAttempts.indexOf(connectionAttempt)!) + private func failConnectionAttempt(_ connectionAttempt: BKConnectionAttempt, error: Error) { + connectionAttempts.remove(at: connectionAttempts.index(of: connectionAttempt)!) connectionAttempt.timer.invalidate() if let peripheral = connectionAttempt.remotePeripheral.peripheral { centralManager.cancelPeripheralConnection(peripheral) @@ -128,9 +128,9 @@ internal class BKConnectionPool: BKCBCentralManagerConnectionDelegate { connectionAttempt.completionHandler(peripheralEntity: connectionAttempt.remotePeripheral, error: error) } - private func succeedConnectionAttempt(connectionAttempt: BKConnectionAttempt) { + private func succeedConnectionAttempt(_ connectionAttempt: BKConnectionAttempt) { connectionAttempt.timer.invalidate() - connectionAttempts.removeAtIndex(connectionAttempts.indexOf(connectionAttempt)!) + connectionAttempts.remove(at: connectionAttempts.index(of: connectionAttempt)!) connectedRemotePeripherals.append(connectionAttempt.remotePeripheral) connectionAttempt.remotePeripheral.discoverServices() connectionAttempt.completionHandler(peripheralEntity: connectionAttempt.remotePeripheral, error: nil) @@ -138,17 +138,17 @@ internal class BKConnectionPool: BKCBCentralManagerConnectionDelegate { // MARK: CentralManagerConnectionDelegate - internal func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) { + internal func centralManager(_ central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) { succeedConnectionAttempt(connectionAttemptForPeripheral(peripheral)!) } - internal func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) { - failConnectionAttempt(connectionAttemptForPeripheral(peripheral)!, error: .Internal(underlyingError: error)) + internal func centralManager(_ central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) { + failConnectionAttempt(connectionAttemptForPeripheral(peripheral)!, error: .internal(underlyingError: error)) } - internal func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) { + internal func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) { if let remotePeripheral = connectedRemotePeripherals.filter({ $0.peripheral == peripheral }).last { - connectedRemotePeripherals.removeAtIndex(connectedRemotePeripherals.indexOf(remotePeripheral)!) + connectedRemotePeripherals.remove(at: connectedRemotePeripherals.index(of: remotePeripheral)!) delegate?.connectionPool(self, remotePeripheralDidDisconnect: remotePeripheral) } } diff --git a/Source/BKContinuousScanner.swift b/Source/BKContinuousScanner.swift index e0ae234..2e806dc 100644 --- a/Source/BKContinuousScanner.swift +++ b/Source/BKContinuousScanner.swift @@ -34,10 +34,10 @@ internal class BKContinousScanner { // MARK: Enums - internal enum Error: ErrorType { - case Busy - case Interrupted - case InternalError(underlyingError: ErrorType) + internal enum Error: ErrorProtocol { + case busy + case interrupted + case internalError(underlyingError: ErrorProtocol) } // MARK: Properties @@ -46,25 +46,25 @@ internal class BKContinousScanner { private let scanner: BKScanner private var busy = false private var maintainedDiscoveries = [BKDiscovery]() - private var inBetweenDelayTimer: NSTimer? + private var inBetweenDelayTimer: Timer? private var errorHandler: ErrorHandler? private var stateHandler: StateHandler? private var changeHandler: ChangeHandler? - private var duration: NSTimeInterval! - private var inBetweenDelay: NSTimeInterval! + private var duration: TimeInterval! + private var inBetweenDelay: TimeInterval! // MARK: Initialization internal init(scanner: BKScanner) { self.scanner = scanner - state = .Stopped + state = .stopped } // MARK Internal Functions - internal func scanContinuouslyWithChangeHandler(changeHandler: ChangeHandler, stateHandler: StateHandler? = nil, duration: NSTimeInterval = 3, inBetweenDelay: NSTimeInterval = 3, errorHandler: ErrorHandler?) { + internal func scanContinuouslyWithChangeHandler(_ changeHandler: ChangeHandler, stateHandler: StateHandler? = nil, duration: TimeInterval = 3, inBetweenDelay: TimeInterval = 3, errorHandler: ErrorHandler?) { guard !busy else { - errorHandler?(error: .Busy) + errorHandler?(error: .busy) return } busy = true @@ -78,39 +78,39 @@ internal class BKContinousScanner { internal func interruptScan() { scanner.interruptScan() - endScanning(.Interrupted) + endScanning(.interrupted) } // MARK: Private Functions private func scan() { do { - state = .Scanning + state = .scanning stateHandler?(newState: state) try scanner.scanWithDuration(duration, progressHandler: { newDiscoveries in let actualDiscoveries = newDiscoveries.filter({ !self.maintainedDiscoveries.contains($0) }) if !actualDiscoveries.isEmpty { self.maintainedDiscoveries += actualDiscoveries - let changes = actualDiscoveries.map({ BKDiscoveriesChange.Insert(discovery: $0) }) + let changes = actualDiscoveries.map({ BKDiscoveriesChange.insert(discovery: $0) }) self.changeHandler?(changes: changes, discoveries: self.maintainedDiscoveries) } }, completionHandler: { result, error in guard result != nil && error == nil else { - self.endScanning(Error.InternalError(underlyingError: error!)) + self.endScanning(Error.internalError(underlyingError: error!)) return } let discoveriesToRemove = self.maintainedDiscoveries.filter({ !result!.contains($0) }) - let changes = discoveriesToRemove.map({ BKDiscoveriesChange.Remove(discovery: $0) }) + let changes = discoveriesToRemove.map({ BKDiscoveriesChange.remove(discovery: $0) }) for discoveryToRemove in discoveriesToRemove { - self.maintainedDiscoveries.removeAtIndex(self.maintainedDiscoveries.indexOf(discoveryToRemove)!) + self.maintainedDiscoveries.remove(at: self.maintainedDiscoveries.index(of: discoveryToRemove)!) } self.changeHandler?(changes: changes, discoveries: self.maintainedDiscoveries) - self.state = .Waiting + self.state = .waiting self.stateHandler?(newState: self.state) - self.inBetweenDelayTimer = NSTimer.scheduledTimerWithTimeInterval(self.inBetweenDelay, target: self, selector: #selector(BKContinousScanner.inBetweenDelayTimerElapsed), userInfo: nil, repeats: false) + self.inBetweenDelayTimer = Timer.scheduledTimer(timeInterval: self.inBetweenDelay, target: self, selector: #selector(BKContinousScanner.inBetweenDelayTimerElapsed), userInfo: nil, repeats: false) }) } catch let error { - endScanning(Error.InternalError(underlyingError: error)) + endScanning(Error.internalError(underlyingError: error)) } } @@ -122,9 +122,9 @@ internal class BKContinousScanner { changeHandler = nil } - private func endScanning(error: Error?) { + private func endScanning(_ error: Error?) { busy = false - state = .Stopped + state = .stopped let errorHandler = self.errorHandler let stateHandler = self.stateHandler reset() diff --git a/Source/BKDiscoveriesChange.swift b/Source/BKDiscoveriesChange.swift index 8a7d5fc..2be3591 100644 --- a/Source/BKDiscoveriesChange.swift +++ b/Source/BKDiscoveriesChange.swift @@ -26,8 +26,8 @@ import Foundation public func == (lhs: BKDiscoveriesChange, rhs: BKDiscoveriesChange) -> Bool { switch (lhs, rhs) { - case (.Insert(let lhsDiscovery), .Insert(let rhsDiscovery)): return lhsDiscovery == rhsDiscovery || lhsDiscovery == nil || rhsDiscovery == nil - case (.Remove(let lhsDiscovery), .Remove(let rhsDiscovery)): return lhsDiscovery == rhsDiscovery || lhsDiscovery == nil || rhsDiscovery == nil + case (.insert(let lhsDiscovery), .insert(let rhsDiscovery)): return lhsDiscovery == rhsDiscovery || lhsDiscovery == nil || rhsDiscovery == nil + case (.remove(let lhsDiscovery), .remove(let rhsDiscovery)): return lhsDiscovery == rhsDiscovery || lhsDiscovery == nil || rhsDiscovery == nil default: return false } } @@ -41,14 +41,14 @@ public func == (lhs: BKDiscoveriesChange, rhs: BKDiscoveriesChange) -> Bool { */ public enum BKDiscoveriesChange: Equatable { - case Insert(discovery: BKDiscovery?) - case Remove(discovery: BKDiscovery?) + case insert(discovery: BKDiscovery?) + case remove(discovery: BKDiscovery?) /// The discovery associated with the change. public var discovery: BKDiscovery! { switch self { - case .Insert(let discovery): return discovery - case .Remove(let discovery): return discovery + case .insert(let discovery): return discovery + case .remove(let discovery): return discovery } } diff --git a/Source/BKErrorDomain.swift b/Source/BKErrorDomain.swift index 650c779..e05718b 100644 --- a/Source/BKErrorDomain.swift +++ b/Source/BKErrorDomain.swift @@ -31,9 +31,9 @@ import Foundation - RemotePeerNotConnected: The action failed because the remote peer attempted to interact with, was not connected. - InternalError(underlyingError): Will be returned if any of the internal or private classes returns an unhandled error. */ -public enum BKError: ErrorType { - case InterruptedByUnavailability(cause: BKUnavailabilityCause) - case FailedToConnectDueToTimeout - case RemotePeerNotConnected - case InternalError(underlyingError: ErrorType?) +public enum BKError: ErrorProtocol { + case interruptedByUnavailability(cause: BKUnavailabilityCause) + case failedToConnectDueToTimeout + case remotePeerNotConnected + case internalError(underlyingError: ErrorProtocol?) } diff --git a/Source/BKPeer.swift b/Source/BKPeer.swift index d82048d..6b46ad7 100644 --- a/Source/BKPeer.swift +++ b/Source/BKPeer.swift @@ -24,7 +24,7 @@ import Foundation -public typealias BKSendDataCompletionHandler = ((data: NSData, remotePeer: BKRemotePeer, error: BKError?) -> Void) +public typealias BKSendDataCompletionHandler = ((data: Data, remotePeer: BKRemotePeer, error: BKError?) -> Void) public class BKPeer { @@ -52,9 +52,9 @@ public class BKPeer { - parameter remotePeer: The destination of the data payload. - parameter completionHandler: A completion handler allowing you to react in case the data failed to send or once it was sent succesfully. */ - public func sendData(data: NSData, toRemotePeer remotePeer: BKRemotePeer, completionHandler: BKSendDataCompletionHandler?) { + public func sendData(_ data: Data, toRemotePeer remotePeer: BKRemotePeer, completionHandler: BKSendDataCompletionHandler?) { guard connectedRemotePeers.contains(remotePeer) else { - completionHandler?(data: data, remotePeer: remotePeer, error: BKError.RemotePeerNotConnected) + completionHandler?(data: data, remotePeer: remotePeer, error: BKError.remotePeerNotConnected) return } let sendDataTask = BKSendDataTask(data: data, destination: remotePeer, completionHandler: completionHandler) @@ -70,33 +70,37 @@ public class BKPeer { } let nextTask = sendDataTasks.first! if nextTask.sentAllData { - let sentEndOfDataMark = sendData(configuration!.endOfDataMark, toRemotePeer: nextTask.destination) + let sentEndOfDataMark = sendData(configuration!.endOfDataMark as Data, toRemotePeer: nextTask.destination) if sentEndOfDataMark { - sendDataTasks.removeAtIndex(sendDataTasks.indexOf(nextTask)!) - nextTask.completionHandler?(data: nextTask.data, remotePeer: nextTask.destination, error: nil) + sendDataTasks.remove(at: sendDataTasks.index(of: nextTask)!) + nextTask.completionHandler?(data: nextTask.data as Data, remotePeer: nextTask.destination, error: nil) processSendDataTasks() } else { return } } - let nextPayload = nextTask.nextPayload - let sentNextPayload = sendData(nextPayload, toRemotePeer: nextTask.destination) - if sentNextPayload { - nextTask.offset += nextPayload.length - processSendDataTasks() + if let nextPayload = nextTask.nextPayload { + let sentNextPayload = sendData(nextPayload as Data, toRemotePeer: nextTask.destination) + if sentNextPayload { + nextTask.offset += nextPayload.count + processSendDataTasks() + } else { + return + } } else { return } + } - internal func failSendDataTasksForRemotePeer(remotePeer: BKRemotePeer) { + internal func failSendDataTasksForRemotePeer(_ remotePeer: BKRemotePeer) { for sendDataTask in sendDataTasks.filter({ $0.destination == remotePeer }) { - sendDataTasks.removeAtIndex(sendDataTasks.indexOf(sendDataTask)!) - sendDataTask.completionHandler?(data: sendDataTask.data, remotePeer: sendDataTask.destination, error: .RemotePeerNotConnected) + sendDataTasks.remove(at: sendDataTasks.index(of: sendDataTask)!) + sendDataTask.completionHandler?(data: sendDataTask.data as Data, remotePeer: sendDataTask.destination, error: .remotePeerNotConnected) } } - internal func sendData(data: NSData, toRemotePeer remotePeer: BKRemotePeer) -> Bool { + internal func sendData(_ data: Data, toRemotePeer remotePeer: BKRemotePeer) -> Bool { fatalError("Function must be overridden by subclass") } diff --git a/Source/BKPeripheral.swift b/Source/BKPeripheral.swift index 6592af2..0b1d4db 100644 --- a/Source/BKPeripheral.swift +++ b/Source/BKPeripheral.swift @@ -28,30 +28,33 @@ import CoreBluetooth /** The peripheral's delegate is called when asynchronous events occur. */ +@available(iOS 10.0, *) public protocol BKPeripheralDelegate: class { /** Called when a remote central connects and is ready to receive data. - parameter peripheral: The peripheral object to which the remote central connected. - parameter remoteCentral: The remote central that connected. */ - func peripheral(peripheral: BKPeripheral, remoteCentralDidConnect remoteCentral: BKRemoteCentral) + func peripheral(_ peripheral: BKPeripheral, remoteCentralDidConnect remoteCentral: BKRemoteCentral) /** Called when a remote central disconnects and can no longer receive data. - parameter peripheral: The peripheral object from which the remote central disconnected. - parameter remoteCentral: The remote central that disconnected. */ - func peripheral(peripheral: BKPeripheral, remoteCentralDidDisconnect remoteCentral: BKRemoteCentral) + func peripheral(_ peripheral: BKPeripheral, remoteCentralDidDisconnect remoteCentral: BKRemoteCentral) } /** The class used to take the Bluetooth LE peripheral role. Peripherals can be discovered and connected to by centrals. One a central has connected, the peripheral can send data to it. */ +@available(iOS 10.0, *) public class BKPeripheral: BKPeer, BKCBPeripheralManagerDelegate, BKAvailabilityObservable { // MARK: Properies /// Bluetooth LE availability derived from the underlying CBPeripheralManager object. + @available(iOS 10.0, *) public var availability: BKAvailability { return BKAvailability(peripheralManagerState: peripheralManager.state) } @@ -99,13 +102,13 @@ public class BKPeripheral: BKPeer, BKCBPeripheralManagerDelegate, BKAvailability - parameter configuration: A configuration defining the unique identifiers along with the name to be broadcasted. - throws: An internal error if the BKPeripheral object was already started. */ - public func startWithConfiguration(configuration: BKPeripheralConfiguration) throws { + public func startWithConfiguration(_ configuration: BKPeripheralConfiguration) throws { do { - try stateMachine.handleEvent(.Start) + try stateMachine.handleEvent(event: .start) _configuration = configuration peripheralManager = CBPeripheralManager(delegate: peripheralManagerDelegate, queue: nil, options: nil) } catch let error { - throw BKError.InternalError(underlyingError: error) + throw BKError.internalError(underlyingError: error) } } @@ -115,7 +118,7 @@ public class BKPeripheral: BKPeer, BKCBPeripheralManagerDelegate, BKAvailability */ public func stop() throws { do { - try stateMachine.handleEvent(.Stop) + try stateMachine.handleEvent(event: .stop) _configuration = nil if peripheralManager.isAdvertising { peripheralManager.stopAdvertising() @@ -123,13 +126,13 @@ public class BKPeripheral: BKPeer, BKCBPeripheralManagerDelegate, BKAvailability peripheralManager.removeAllServices() peripheralManager = nil } catch let error { - throw BKError.InternalError(underlyingError: error) + throw BKError.internalError(underlyingError: error) } } // MARK: Private Functions - private func setUnavailable(cause: BKUnavailabilityCause, oldCause: BKUnavailabilityCause?) { + private func setUnavailable(_ cause: BKUnavailabilityCause, oldCause: BKUnavailabilityCause?) { if oldCause == nil { for remotePeer in connectedRemotePeers { if let remoteCentral = remotePeer as? BKRemoteCentral { @@ -137,7 +140,7 @@ public class BKPeripheral: BKPeer, BKCBPeripheralManagerDelegate, BKAvailability } } for availabilityObserver in availabilityObservers { - availabilityObserver.availabilityObserver?.availabilityObserver(self, availabilityDidChange: .Unavailable(cause: cause)) + availabilityObserver.availabilityObserver?.availabilityObserver(self, availabilityDidChange: .unavailable(cause: cause)) } } else if oldCause != nil && oldCause != cause { for availabilityObserver in availabilityObservers { @@ -148,53 +151,53 @@ public class BKPeripheral: BKPeer, BKCBPeripheralManagerDelegate, BKAvailability private func setAvailable() { for availabilityObserver in availabilityObservers { - availabilityObserver.availabilityObserver?.availabilityObserver(self, availabilityDidChange: .Available) + availabilityObserver.availabilityObserver?.availabilityObserver(self, availabilityDidChange: .available) } if !peripheralManager.isAdvertising { dataService = CBMutableService(type: _configuration.dataServiceUUID, primary: true) - let properties: CBCharacteristicProperties = [ .Read, .Notify, .WriteWithoutResponse, .Write ] - let permissions: CBAttributePermissions = [ .Readable, .Writeable ] + let properties: CBCharacteristicProperties = [ .read, .notify, .writeWithoutResponse, .write ] + let permissions: CBAttributePermissions = [ .readable, .writeable ] characteristicData = CBMutableCharacteristic(type: _configuration.dataServiceCharacteristicUUID, properties: properties, value: nil, permissions: permissions) dataService.characteristics = [ characteristicData ] - peripheralManager.addService(dataService) + peripheralManager.add(dataService) } } - internal override func sendData(data: NSData, toRemotePeer remotePeer: BKRemotePeer) -> Bool { + internal override func sendData(_ data: Data, toRemotePeer remotePeer: BKRemotePeer) -> Bool { guard let remoteCentral = remotePeer as? BKRemoteCentral else { return false } - return peripheralManager.updateValue(data, forCharacteristic: characteristicData, onSubscribedCentrals: [ remoteCentral.central ]) + return peripheralManager.updateValue(data, for: characteristicData, onSubscribedCentrals: [ remoteCentral.central ]) } - private func handleDisconnectForRemoteCentral(remoteCentral: BKRemoteCentral) { + private func handleDisconnectForRemoteCentral(_ remoteCentral: BKRemoteCentral) { failSendDataTasksForRemotePeer(remoteCentral) - connectedRemotePeers.removeAtIndex(connectedRemotePeers.indexOf(remoteCentral)!) + connectedRemotePeers.remove(at: connectedRemotePeers.index(of: remoteCentral)!) delegate?.peripheral(self, remoteCentralDidDisconnect: remoteCentral) } // MARK: BKCBPeripheralManagerDelegate - internal func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) { + internal func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { switch peripheral.state { - case .Unknown, .Resetting: + case .unknown, .resetting: break - case .Unsupported, .Unauthorized, .PoweredOff: + case .unsupported, .unauthorized, .poweredOff: let newCause = BKUnavailabilityCause(peripheralManagerState: peripheral.state) switch stateMachine.state { - case let .Unavailable(cause): + case let .unavailable(cause): let oldCause = cause - _ = try? stateMachine.handleEvent(.SetUnavailable(cause: newCause)) + _ = try? stateMachine.handleEvent(event: .setUnavailable(cause: newCause)) setUnavailable(oldCause, oldCause: newCause) default: - _ = try? stateMachine.handleEvent(.SetUnavailable(cause: newCause)) + _ = try? stateMachine.handleEvent(event: .setUnavailable(cause: newCause)) setUnavailable(newCause, oldCause: nil) } - case .PoweredOn: + case .poweredOn: let state = stateMachine.state - _ = try? stateMachine.handleEvent(.SetAvailable) + _ = try? stateMachine.handleEvent(event: .setAvailable) switch state { - case .Starting, .Unavailable: + case .starting, .unavailable: setAvailable() default: break @@ -202,11 +205,11 @@ public class BKPeripheral: BKPeer, BKCBPeripheralManagerDelegate, BKAvailability } } - internal func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager, error: NSError?) { + internal func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: NSError?) { } - internal func peripheralManager(peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) { + internal func peripheralManager(_ peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) { if !peripheralManager.isAdvertising { var advertisementData: [String: AnyObject] = [ CBAdvertisementDataServiceUUIDsKey: _configuration.serviceUUIDs ] if let localName = _configuration.localName { @@ -216,22 +219,22 @@ public class BKPeripheral: BKPeer, BKCBPeripheralManagerDelegate, BKAvailability } } - internal func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didSubscribeToCharacteristic characteristic: CBCharacteristic) { + internal func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeToCharacteristic characteristic: CBCharacteristic) { let remoteCentral = BKRemoteCentral(central: central) remoteCentral.configuration = configuration connectedRemotePeers.append(remoteCentral) delegate?.peripheral(self, remoteCentralDidConnect: remoteCentral) } - internal func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFromCharacteristic characteristic: CBCharacteristic) { - if let remoteCentral = connectedRemotePeers.filter({ $0.identifier.isEqual(central.identifier) }).last as? BKRemoteCentral { + internal func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFromCharacteristic characteristic: CBCharacteristic) { + if let remoteCentral = connectedRemotePeers.filter({ ($0.identifier == central.identifier) }).last as? BKRemoteCentral { handleDisconnectForRemoteCentral(remoteCentral) } } - func peripheralManager(peripheral: CBPeripheralManager, didReceiveWriteRequests requests: [CBATTRequest]) { + func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWriteRequests requests: [CBATTRequest]) { for writeRequest in requests { - guard writeRequest.characteristic.UUID == characteristicData.UUID else { + guard writeRequest.characteristic.uuid == characteristicData.uuid else { continue } guard let remotePeer = (connectedRemotePeers.filter { $0.identifier == writeRequest.central.identifier } .last), remoteCentral = remotePeer as? BKRemoteCentral, data = writeRequest.value else { @@ -241,7 +244,7 @@ public class BKPeripheral: BKPeer, BKCBPeripheralManagerDelegate, BKAvailability } } - internal func peripheralManagerIsReadyToUpdateSubscribers(peripheral: CBPeripheralManager) { + internal func peripheralManagerIsReadyToUpdateSubscribers(_ peripheral: CBPeripheralManager) { processSendDataTasks() } diff --git a/Source/BKPeripheralConfiguration.swift b/Source/BKPeripheralConfiguration.swift index 3a2ee4b..0e81cd7 100644 --- a/Source/BKPeripheralConfiguration.swift +++ b/Source/BKPeripheralConfiguration.swift @@ -37,7 +37,7 @@ public class BKPeripheralConfiguration: BKConfiguration { // MARK: Initialization - public init(dataServiceUUID: NSUUID, dataServiceCharacteristicUUID: NSUUID, localName: String? = nil) { + public init(dataServiceUUID: UUID, dataServiceCharacteristicUUID: UUID, localName: String? = nil) { self.localName = localName super.init(dataServiceUUID: dataServiceUUID, dataServiceCharacteristicUUID: dataServiceCharacteristicUUID) } diff --git a/Source/BKPeripheralStateMachine.swift b/Source/BKPeripheralStateMachine.swift index bc1dfb1..79e91fe 100644 --- a/Source/BKPeripheralStateMachine.swift +++ b/Source/BKPeripheralStateMachine.swift @@ -28,16 +28,16 @@ internal class BKPeripheralStateMachine { // MARK: Enums - internal enum Error: ErrorType { - case Transitioning(currentState: State, validStates: [State]) + internal enum Error: ErrorProtocol { + case transitioning(currentState: State, validStates: [State]) } internal enum State { - case Initialized, Starting, Unavailable(cause: BKUnavailabilityCause), Available + case initialized, starting, unavailable(cause: BKUnavailabilityCause), available } internal enum Event { - case Start, SetUnavailable(cause: BKUnavailabilityCause), SetAvailable, Stop + case start, setUnavailable(cause: BKUnavailabilityCause), setAvailable, stop } // MARK: Properties @@ -47,57 +47,57 @@ internal class BKPeripheralStateMachine { // MARK: Initialization internal init() { - self.state = .Initialized + self.state = .initialized } // MARK: Functions internal func handleEvent(event: Event) throws { switch event { - case .Start: - try handleStartEvent(event) - case .SetAvailable: - try handleSetAvailableEvent(event) - case let .SetUnavailable(cause): - try handleSetUnavailableEvent(event, withCause: cause) - case .Stop: - try handleStopEvent(event) + case .start: + try handleStartEvent(event: event) + case .setAvailable: + try handleSetAvailableEvent(event: event) + case let .setUnavailable(cause): + try handleSetUnavailableEvent(event: event, withCause: cause) + case .stop: + try handleStopEvent(event: event) } } private func handleStartEvent(event: Event) throws { switch state { - case .Initialized: - state = .Starting + case .initialized: + state = .starting default: - throw Error.Transitioning(currentState: state, validStates: [ .Initialized ]) + throw Error.transitioning(currentState: state, validStates: [ .initialized ]) } } private func handleSetAvailableEvent(event: Event) throws { switch state { - case .Initialized: - throw Error.Transitioning(currentState: state, validStates: [ .Starting, .Available, .Unavailable(cause: nil) ]) + case .initialized: + throw Error.transitioning(currentState: state, validStates: [ .starting, .available, .unavailable(cause: nil) ]) default: - state = .Available + state = .available } } private func handleSetUnavailableEvent(event: Event, withCause cause: BKUnavailabilityCause) throws { switch state { - case .Initialized: - throw Error.Transitioning(currentState: state, validStates: [ .Starting, .Available, .Unavailable(cause: nil) ]) + case .initialized: + throw Error.transitioning(currentState: state, validStates: [ .starting, .available, .unavailable(cause: nil) ]) default: - state = .Unavailable(cause: cause) + state = .unavailable(cause: cause) } } private func handleStopEvent(event: Event) throws { switch state { - case .Initialized: - throw Error.Transitioning(currentState: state, validStates: [ .Starting, .Available, .Unavailable(cause: nil) ]) + case .initialized: + throw Error.transitioning(currentState: state, validStates: [ .starting, .available, .unavailable(cause: nil) ]) default: - state = .Initialized + state = .initialized } } diff --git a/Source/BKRemotePeer.swift b/Source/BKRemotePeer.swift index 5a4961f..102a69a 100644 --- a/Source/BKRemotePeer.swift +++ b/Source/BKRemotePeer.swift @@ -30,24 +30,24 @@ public protocol BKRemotePeerDelegate: class { - parameter remotePeripheral: The remote peripheral that sent the data. - parameter data: The data it sent. */ - func remotePeer(remotePeer: BKRemotePeer, didSendArbitraryData data: NSData) + func remotePeer(_ remotePeer: BKRemotePeer, didSendArbitraryData data: Data) } public func == (lhs: BKRemotePeer, rhs: BKRemotePeer) -> Bool { - return lhs.identifier.isEqual(rhs.identifier) + return (lhs.identifier == rhs.identifier) } public class BKRemotePeer: Equatable { /// A unique identifier for the peer, derived from the underlying CBCentral or CBPeripheral object, or set manually. - public let identifier: NSUUID + public let identifier: UUID public weak var delegate: BKRemotePeerDelegate? internal var configuration: BKConfiguration? private var data: NSMutableData? - init(identifier: NSUUID) { + init(identifier: UUID) { self.identifier = identifier } @@ -55,19 +55,19 @@ public class BKRemotePeer: Equatable { return 20 } - internal func handleReceivedData(receivedData: NSData) { - if receivedData.isEqualToData(configuration!.endOfDataMark) { + internal func handleReceivedData(_ receivedData: Data) { + if receivedData == configuration!.endOfDataMark { if let finalData = data { - delegate?.remotePeer(self, didSendArbitraryData: finalData) + delegate?.remotePeer(self, didSendArbitraryData: finalData as Data) } data = nil return } if let existingData = data { - existingData.appendData(receivedData) + existingData.append(receivedData) return } - data = NSMutableData(data: receivedData) + data = NSData(data: receivedData) as? NSMutableData } } diff --git a/Source/BKRemotePeripheral.swift b/Source/BKRemotePeripheral.swift index c5eca40..8d0dd4f 100644 --- a/Source/BKRemotePeripheral.swift +++ b/Source/BKRemotePeripheral.swift @@ -34,7 +34,7 @@ public protocol BKRemotePeripheralDelegate: class { - parameter remotePeripheral: The remote peripheral that updated its name. - parameter name: The new name. */ - func remotePeripheral(remotePeripheral: BKRemotePeripheral, didUpdateName name: String) + func remotePeripheral(_ remotePeripheral: BKRemotePeripheral, didUpdateName name: String) } /** @@ -53,7 +53,7 @@ public class BKRemotePeripheral: BKRemotePeer, BKCBPeripheralDelegate { - Disconnecting: The peripheral is currently disconnecting. */ public enum State { - case Shallow, Disconnected, Connecting, Connected, Disconnecting + case shallow, disconnected, connecting, connected, disconnecting } // MARK: Properties @@ -61,14 +61,14 @@ public class BKRemotePeripheral: BKRemotePeer, BKCBPeripheralDelegate { /// The current state of the remote peripheral, either shallow or derived from an underlying CBPeripheral object. public var state: State { if peripheral == nil { - return .Shallow + return .shallow } #if os(iOS) || os(tvOS) switch peripheral!.state { - case .Disconnected: return .Disconnected - case .Connecting: return .Connecting - case .Connected: return .Connected - case .Disconnecting: return .Disconnecting + case .disconnected: return .disconnected + case .connecting: return .connecting + case .connected: return .connected + case .disconnecting: return .disconnecting } #else switch peripheral!.state { @@ -94,7 +94,7 @@ public class BKRemotePeripheral: BKRemotePeer, BKCBPeripheralDelegate { #if os(OSX) return super.maximumUpdateValueLength #else - return peripheral.maximumWriteValueLengthForType(.WithoutResponse) + return peripheral.maximumWriteValueLength(for: .withoutResponse) #endif } @@ -105,7 +105,7 @@ public class BKRemotePeripheral: BKRemotePeer, BKCBPeripheralDelegate { // MARK: Initialization - public init(identifier: NSUUID, peripheral: CBPeripheral?) { + public init(identifier: UUID, peripheral: CBPeripheral?) { super.init(identifier: identifier) self.peripheralDelegateProxy = BKCBPeripheralDelegateProxy(delegate: self) self.peripheral = peripheral @@ -134,18 +134,18 @@ public class BKRemotePeripheral: BKRemotePeer, BKCBPeripheralDelegate { continue } for characteristic in service.characteristics! { - peripheral?.setNotifyValue(false, forCharacteristic: characteristic) + peripheral?.setNotifyValue(false, for: characteristic) } } } // MARK: BKCBPeripheralDelegate - internal func peripheralDidUpdateName(peripheral: CBPeripheral) { + internal func peripheralDidUpdateName(_ peripheral: CBPeripheral) { peripheralDelegate?.remotePeripheral(self, didUpdateName: name!) } - internal func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) { + internal func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: NSError?) { guard let services = peripheral.services else { return } @@ -153,21 +153,21 @@ public class BKRemotePeripheral: BKRemotePeer, BKCBPeripheralDelegate { if service.characteristics != nil { self.peripheral(peripheral, didDiscoverCharacteristicsForService: service, error: nil) } else { - peripheral.discoverCharacteristics(configuration!.characteristicUUIDsForServiceUUID(service.UUID), forService: service) + peripheral.discoverCharacteristics(configuration!.characteristicUUIDsForServiceUUID(service.uuid), for: service) } } } - internal func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) { - guard service.UUID == configuration!.dataServiceUUID, let dataCharacteristic = service.characteristics?.filter({ $0.UUID == configuration!.dataServiceCharacteristicUUID }).last else { + internal func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) { + guard service.uuid == configuration!.dataServiceUUID, let dataCharacteristic = service.characteristics?.filter({ $0.uuid == configuration!.dataServiceCharacteristicUUID }).last else { return } characteristicData = dataCharacteristic - peripheral.setNotifyValue(true, forCharacteristic: dataCharacteristic) + peripheral.setNotifyValue(true, for: dataCharacteristic) } - internal func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) { - guard characteristic.UUID == configuration!.dataServiceCharacteristicUUID else { + internal func peripheral(_ peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) { + guard characteristic.uuid == configuration!.dataServiceCharacteristicUUID else { return } handleReceivedData(characteristic.value!) diff --git a/Source/BKScanner.swift b/Source/BKScanner.swift index 373af8f..e6bf7d7 100644 --- a/Source/BKScanner.swift +++ b/Source/BKScanner.swift @@ -33,10 +33,10 @@ internal class BKScanner: BKCBCentralManagerDiscoveryDelegate { // MARK: Enums - internal enum Error: ErrorType { - case NoCentralManagerSet - case Busy - case Interrupted + internal enum Error: ErrorProtocol { + case noCentralManagerSet + case busy + case interrupted } // MARK: Properties @@ -46,17 +46,17 @@ internal class BKScanner: BKCBCentralManagerDiscoveryDelegate { private var busy = false private var scanHandlers: ( progressHandler: BKCentral.ScanProgressHandler?, completionHandler: ScanCompletionHandler )? private var discoveries = [BKDiscovery]() - private var durationTimer: NSTimer? + private var durationTimer: Timer? // MARK: Internal Functions - internal func scanWithDuration(duration: NSTimeInterval, progressHandler: BKCentral.ScanProgressHandler? = nil, completionHandler: ScanCompletionHandler) throws { + internal func scanWithDuration(_ duration: TimeInterval, progressHandler: BKCentral.ScanProgressHandler? = nil, completionHandler: ScanCompletionHandler) throws { do { try validateForActivity() busy = true scanHandlers = (progressHandler: progressHandler, completionHandler: completionHandler) - centralManager.scanForPeripheralsWithServices(configuration.serviceUUIDs, options: nil) - durationTimer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: #selector(BKScanner.durationTimerElapsed), userInfo: nil, repeats: false) + centralManager.scanForPeripherals(withServices: configuration.serviceUUIDs, options: nil) + durationTimer = Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(BKScanner.durationTimerElapsed), userInfo: nil, repeats: false) } catch let error { throw error } @@ -66,17 +66,17 @@ internal class BKScanner: BKCBCentralManagerDiscoveryDelegate { guard busy else { return } - endScan(.Interrupted) + endScan(.interrupted) } // MARK: Private Functions private func validateForActivity() throws { guard !busy else { - throw Error.Busy + throw Error.busy } guard centralManager != nil else { - throw Error.NoCentralManagerSet + throw Error.noCentralManagerSet } } @@ -84,7 +84,7 @@ internal class BKScanner: BKCBCentralManagerDiscoveryDelegate { endScan(nil) } - private func endScan(error: Error?) { + private func endScan(_ error: Error?) { invalidateTimer() centralManager.stopScan() let completionHandler = scanHandlers?.completionHandler @@ -104,7 +104,7 @@ internal class BKScanner: BKCBCentralManagerDiscoveryDelegate { // MARK: BKCBCentralManagerDiscoveryDelegate - internal func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String: AnyObject], RSSI: NSNumber) { + internal func centralManager(_ central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String: AnyObject], RSSI: NSNumber) { guard busy else { return } diff --git a/Source/BKSendDataTask.swift b/Source/BKSendDataTask.swift index 28d2e40..b016da5 100644 --- a/Source/BKSendDataTask.swift +++ b/Source/BKSendDataTask.swift @@ -25,14 +25,14 @@ import Foundation internal func == (lhs: BKSendDataTask, rhs: BKSendDataTask) -> Bool { - return lhs.destination == rhs.destination && lhs.data.isEqualToData(rhs.data) + return lhs.destination == rhs.destination && lhs.data == rhs.data } internal class BKSendDataTask: Equatable { // MARK: Properties - internal let data: NSData + internal let data: Data internal let destination: BKRemotePeer internal let completionHandler: BKSendDataCompletionHandler? internal var offset = 0 @@ -42,25 +42,30 @@ internal class BKSendDataTask: Equatable { } internal var lengthOfRemainingData: Int { - return data.length - offset + return data.count - offset } internal var sentAllData: Bool { return lengthOfRemainingData == 0 } - internal var rangeForNextPayload: NSRange { + internal var rangeForNextPayload: Range? { let lenghtOfNextPayload = maximumPayloadLength <= lengthOfRemainingData ? maximumPayloadLength : lengthOfRemainingData - return NSRange(location: offset, length: lenghtOfNextPayload) + let payLoadRange = NSRange(location: offset, length: lenghtOfNextPayload) + return payLoadRange.toRange() } - internal var nextPayload: NSData { - return data.subdataWithRange(rangeForNextPayload) + internal var nextPayload: Data? { + if let range = rangeForNextPayload { + return data.subdata(in: range) + } else { + return nil + } } // MARK: Initialization - internal init(data: NSData, destination: BKRemotePeer, completionHandler: BKSendDataCompletionHandler?) { + internal init(data: Data, destination: BKRemotePeer, completionHandler: BKSendDataCompletionHandler?) { self.data = data self.destination = destination self.completionHandler = completionHandler