瀏覽代碼

Upgrade to Swift 3

Therin Irwin 9 年之前
父節點
當前提交
106a1d21f6

+ 30 - 24
KeychainSwift/KeychainSwift.swift

@@ -54,10 +54,11 @@ public class KeychainSwift {
    - returns: True if the text was successfully written to the keychain.
 
   */
-  public func set(value: String, forKey key: String,
+  @discardableResult
+  public func set(_ value: String, forKey key: String,
                   withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
     
-    if let value = value.dataUsingEncoding(NSUTF8StringEncoding) {
+    if let value = value.data(using: String.Encoding.utf8) {
       return set(value, forKey: key, withAccess: access)
     }
     
@@ -75,10 +76,11 @@ public class KeychainSwift {
   - returns: True if the text was successfully written to the keychain.
   
   */
-  public func set(value: NSData, forKey key: String,
+  @discardableResult
+  public func set(_ value: Data, forKey key: String,
     withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
     
-    delete(key) // Delete any existing key before saving it
+    _ = delete(key) // Delete any existing key before saving it
 
     let accessible = access?.value ?? KeychainSwiftAccessOptions.defaultOption.value
       
@@ -91,11 +93,11 @@ public class KeychainSwift {
       KeychainSwiftConstants.accessible  : accessible
     ]
       
-    query = addAccessGroupWhenPresent(query)
-    query = addSynchronizableIfRequired(query, addingItems: true)
-    lastQueryParameters = query
+    query = addAccessGroupWhenPresent(query as! [String : NSObject])
+    query = addSynchronizableIfRequired(query as! [String : NSObject], addingItems: true)
+    lastQueryParameters = query as? [String: NSObject]
     
-    lastResultCode = SecItemAdd(query as CFDictionaryRef, nil)
+    lastResultCode = SecItemAdd(query as CFDictionary, nil)
     
     return lastResultCode == noErr
   }
@@ -111,11 +113,13 @@ public class KeychainSwift {
   - returns: True if the value was successfully written to the keychain.
 
   */
-  public func set(value: Bool, forKey key: String,
+  @discardableResult
+  public func set(_ value: Bool, forKey key: String,
     withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool {
 
-    var localValue = value
-    let data = NSData(bytes: &localValue, length: sizeof(Bool))
+    var bits = unsafeBitCast(value, to: UInt8.self)
+    let data = Data(bytes: &bits, count: sizeof(Bool))
+
     return set(data, forKey: key, withAccess: access)
   }
 
@@ -127,9 +131,9 @@ public class KeychainSwift {
   - returns: The text value from the keychain. Returns nil if unable to read the item.
   
   */
-  public func get(key: String) -> String? {
+  public func get(_ key: String) -> String? {
     if let data = getData(key) {
-      if let currentString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
+      if let currentString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as? String {
         return currentString
       }
       
@@ -147,7 +151,7 @@ public class KeychainSwift {
   - returns: The text value from the keychain. Returns nil if unable to read the item.
   
   */
-  public func getData(key: String) -> NSData? {
+  public func getData(_ key: String) -> Data? {
     let prefixedKey = keyWithPrefix(key)
     
     var query: [String: NSObject] = [
@@ -167,7 +171,7 @@ public class KeychainSwift {
       SecItemCopyMatching(query, UnsafeMutablePointer($0))
     }
     
-    if lastResultCode == noErr { return result as? NSData }
+    if lastResultCode == noErr { return result as? Data }
     
     return nil
   }
@@ -180,10 +184,10 @@ public class KeychainSwift {
   - returns: The boolean value from the keychain. Returns nil if unable to read the item.
 
   */
-  public func getBool(key: String) -> Bool? {
+  public func getBool(_ key: String) -> Bool? {
     guard let data = getData(key) else { return nil }
     var boolValue = false
-    data.getBytes(&boolValue, length: sizeof(Bool))
+    (data as NSData).getBytes(&boolValue, length: sizeof(Bool))
     return boolValue
   }
 
@@ -195,7 +199,8 @@ public class KeychainSwift {
   - returns: True if the item was successfully deleted.
   
   */
-  public func delete(key: String) -> Bool {
+  @discardableResult
+  public func delete(_ key: String) -> Bool {
     let prefixedKey = keyWithPrefix(key)
 
     var query: [String: NSObject] = [
@@ -207,7 +212,7 @@ public class KeychainSwift {
     query = addSynchronizableIfRequired(query, addingItems: false)
     lastQueryParameters = query
     
-    lastResultCode = SecItemDelete(query as CFDictionaryRef)
+    lastResultCode = SecItemDelete(query as CFDictionary)
     
     return lastResultCode == noErr
   }
@@ -219,23 +224,24 @@ public class KeychainSwift {
   - returns: True if the keychain items were successfully deleted.
   
   */
+  @discardableResult
   public func clear() -> Bool {
     var query: [String: NSObject] = [ kSecClass as String : kSecClassGenericPassword ]
     query = addAccessGroupWhenPresent(query)
     query = addSynchronizableIfRequired(query, addingItems: false)
     lastQueryParameters = query
     
-    lastResultCode = SecItemDelete(query as CFDictionaryRef)
+    lastResultCode = SecItemDelete(query as CFDictionary)
     
     return lastResultCode == noErr
   }
   
   /// Returns the key with currently set prefix.
-  func keyWithPrefix(key: String) -> String {
+  func keyWithPrefix(_ key: String) -> String {
     return "\(keyPrefix)\(key)"
   }
   
-  func addAccessGroupWhenPresent(items: [String: NSObject]) -> [String: NSObject] {
+  func addAccessGroupWhenPresent(_ items: [String: NSObject]) -> [String: NSObject] {
     guard let accessGroup = accessGroup else { return items }
     
     var result: [String: NSObject] = items
@@ -253,10 +259,10 @@ public class KeychainSwift {
    - returns: the dictionary with kSecAttrSynchronizable item added if it was requested. Otherwise, it returns the original dictionary.
  
   */
-  func addSynchronizableIfRequired(items: [String: NSObject], addingItems: Bool) -> [String: NSObject] {
+  func addSynchronizableIfRequired(_ items: [String: NSObject], addingItems: Bool) -> [String: NSObject] {
     if !synchronizable { return items }
     var result: [String: NSObject] = items
     result[KeychainSwiftConstants.attrSynchronizable] = addingItems == true ? true : kSecAttrSynchronizableAny
     return result
   }
-}
+}

+ 17 - 17
KeychainSwift/KeychainSwiftAccessOptions.swift

@@ -16,7 +16,7 @@ public enum KeychainSwiftAccessOptions {
   This is the default value for keychain items added without explicitly setting an accessibility constant.
   
   */
-  case AccessibleWhenUnlocked
+  case accessibleWhenUnlocked
   
   /**
   
@@ -25,7 +25,7 @@ public enum KeychainSwiftAccessOptions {
   This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
   
   */
-  case AccessibleWhenUnlockedThisDeviceOnly
+  case accessibleWhenUnlockedThisDeviceOnly
   
   /**
   
@@ -34,7 +34,7 @@ public enum KeychainSwiftAccessOptions {
   After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute migrate to a new device when using encrypted backups.
   
   */
-  case AccessibleAfterFirstUnlock
+  case accessibleAfterFirstUnlock
   
   /**
   
@@ -43,7 +43,7 @@ public enum KeychainSwiftAccessOptions {
   After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
   
   */
-  case AccessibleAfterFirstUnlockThisDeviceOnly
+  case accessibleAfterFirstUnlockThisDeviceOnly
   
   /**
   
@@ -52,7 +52,7 @@ public enum KeychainSwiftAccessOptions {
   This is not recommended for application use. Items with this attribute migrate to a new device when using encrypted backups.
   
   */
-  case AccessibleAlways
+  case accessibleAlways
   
   /**
   
@@ -61,7 +61,7 @@ public enum KeychainSwiftAccessOptions {
   This is recommended for items that only need to be accessible while the application is in the foreground. Items with this attribute never migrate to a new device. After a backup is restored to a new device, these items are missing. No items can be stored in this class on devices without a passcode. Disabling the device passcode causes all items in this class to be deleted.
   
   */
-  case AccessibleWhenPasscodeSetThisDeviceOnly
+  case accessibleWhenPasscodeSetThisDeviceOnly
   
   /**
   
@@ -70,38 +70,38 @@ public enum KeychainSwiftAccessOptions {
   This is not recommended for application use. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
   
   */
-  case AccessibleAlwaysThisDeviceOnly
+  case accessibleAlwaysThisDeviceOnly
   
   static var defaultOption: KeychainSwiftAccessOptions {
-    return .AccessibleWhenUnlocked
+    return .accessibleWhenUnlocked
   }
   
   var value: String {
     switch self {
-    case .AccessibleWhenUnlocked:
+    case .accessibleWhenUnlocked:
       return toString(kSecAttrAccessibleWhenUnlocked)
       
-    case .AccessibleWhenUnlockedThisDeviceOnly:
+    case .accessibleWhenUnlockedThisDeviceOnly:
       return toString(kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
       
-    case .AccessibleAfterFirstUnlock:
+    case .accessibleAfterFirstUnlock:
       return toString(kSecAttrAccessibleAfterFirstUnlock)
       
-    case .AccessibleAfterFirstUnlockThisDeviceOnly:
+    case .accessibleAfterFirstUnlockThisDeviceOnly:
       return toString(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
       
-    case .AccessibleAlways:
+    case .accessibleAlways:
       return toString(kSecAttrAccessibleAlways)
       
-    case .AccessibleWhenPasscodeSetThisDeviceOnly:
+    case .accessibleWhenPasscodeSetThisDeviceOnly:
       return toString(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
       
-    case .AccessibleAlwaysThisDeviceOnly:
+    case .accessibleAlwaysThisDeviceOnly:
       return toString(kSecAttrAccessibleAlwaysThisDeviceOnly)
     }
   }
   
-  func toString(value: CFStringRef) -> String {
+  func toString(_ value: CFString) -> String {
     return KeychainSwiftConstants.toString(value)
   }
-}
+}

+ 1 - 1
KeychainSwift/TegKeychainConstants.swift

@@ -31,7 +31,7 @@ public struct KeychainSwiftConstants {
   /// Used for specifying a value when setting a Keychain value.
   public static var valueData: String { return toString(kSecValueData) }
   
-  static func toString(value: CFStringRef) -> String {
+  static func toString(_ value: CFString) -> String {
     return value as String
   }
 }

+ 2 - 2
KeychainSwiftTests/AccessGroupTests.swift

@@ -48,7 +48,7 @@ class AccessGroupTests: XCTestCase {
   
   func testGet() {
     obj.accessGroup = "123.my.test.group"
-    obj.get("key 1")
+    _ = obj.get("key 1")
     XCTAssertEqual("123.my.test.group", obj.lastQueryParameters?["agrp"])
   }
   
@@ -63,4 +63,4 @@ class AccessGroupTests: XCTestCase {
     obj.clear()
     XCTAssertEqual("123.my.test.group", obj.lastQueryParameters?["agrp"])
   }
-}
+}

+ 4 - 4
KeychainSwiftTests/KeychainSwiftPrefixedTests.swift

@@ -43,19 +43,19 @@ class KeychainWithPrefixTests: XCTestCase {
   func testSetData() {
     let key = "key 123"
     
-    let dataPrefixed = "prefixed".dataUsingEncoding(NSUTF8StringEncoding)!
-    let dataNonPrefixed = "non prefixed".dataUsingEncoding(NSUTF8StringEncoding)!
+    let dataPrefixed = "prefixed".data(using: String.Encoding.utf8)!
+    let dataNonPrefixed = "non prefixed".data(using: String.Encoding.utf8)!
     
     XCTAssertTrue(prefixed.set(dataPrefixed, forKey: key))
     XCTAssertTrue(nonPrefixed.set(dataNonPrefixed, forKey: key))
 
     
     let dataFromKeychainPrefixed = prefixed.getData(key)!
-    let textFromKeychainPrefixed = NSString(data: dataFromKeychainPrefixed, encoding:NSUTF8StringEncoding) as! String
+    let textFromKeychainPrefixed = String(data: dataFromKeychainPrefixed, encoding: .utf8)!
     XCTAssertEqual("prefixed", textFromKeychainPrefixed)
     
     let dataFromKeychainNonPrefixed = nonPrefixed.getData(key)!
-    let textFromKeychainNonPrefixed = NSString(data: dataFromKeychainNonPrefixed, encoding:NSUTF8StringEncoding) as! String
+    let textFromKeychainNonPrefixed = String(data: dataFromKeychainNonPrefixed, encoding: .utf8)!
     XCTAssertEqual("non prefixed", textFromKeychainNonPrefixed)
   }
   

+ 8 - 8
KeychainSwiftTests/KeychainSwiftTests.swift

@@ -25,35 +25,35 @@ class keychainTests: XCTestCase {
     XCTAssertTrue(obj.set("hello :)", forKey: "key 1"))
     
     let accessValue = obj.lastQueryParameters?[KeychainSwiftConstants.accessible] as? String
-    XCTAssertEqual(KeychainSwiftAccessOptions.AccessibleWhenUnlocked.value, accessValue!)
+    XCTAssertEqual(KeychainSwiftAccessOptions.accessibleWhenUnlocked.value, accessValue!)
   }
   
   func testSetWithAccessOption() {
-    obj.set("hello :)", forKey: "key 1", withAccess: .AccessibleAfterFirstUnlock)
+    obj.set("hello :)", forKey: "key 1", withAccess: .accessibleAfterFirstUnlock)
     let accessValue = obj.lastQueryParameters?[KeychainSwiftConstants.accessible] as? String
-    XCTAssertEqual(KeychainSwiftAccessOptions.AccessibleAfterFirstUnlock.value, accessValue!)
+    XCTAssertEqual(KeychainSwiftAccessOptions.accessibleAfterFirstUnlock.value, accessValue!)
   }
   
   // MARK: - Set data
   // -----------------------
   
   func testSetData() {
-    let data = "hello world".dataUsingEncoding(NSUTF8StringEncoding)!
+    let data = "hello world".data(using: String.Encoding.utf8)!
     
     XCTAssertTrue(obj.set(data, forKey: "key 123"))
     
     let dataFromKeychain = obj.getData("key 123")!
-    let textFromKeychain = NSString(data: dataFromKeychain, encoding:NSUTF8StringEncoding) as! String
+    let textFromKeychain = String(data: dataFromKeychain, encoding:String.Encoding.utf8)!
     XCTAssertEqual("hello world", textFromKeychain)
   }
   
   func testSetData_usesAccessibleWhenUnlockedByDefault() {
-    let data = "hello world".dataUsingEncoding(NSUTF8StringEncoding)!
+    let data = "hello world".data(using: String.Encoding.utf8)!
     
     obj.set(data, forKey: "key 123")
     
     let accessValue = obj.lastQueryParameters?[KeychainSwiftConstants.accessible] as? String
-    XCTAssertEqual(KeychainSwiftAccessOptions.AccessibleWhenUnlocked.value, accessValue!)
+    XCTAssertEqual(KeychainSwiftAccessOptions.accessibleWhenUnlocked.value, accessValue!)
   }
 
   // MARK: - Set bool
@@ -69,7 +69,7 @@ class keychainTests: XCTestCase {
   func testSetBool_usesAccessibleWhenUnlockedByDefault() {
     XCTAssertTrue(obj.set(false, forKey: "key bool"))
     let accessValue = obj.lastQueryParameters?[KeychainSwiftConstants.accessible] as? String
-    XCTAssertEqual(KeychainSwiftAccessOptions.AccessibleWhenUnlocked.value, accessValue!)
+    XCTAssertEqual(KeychainSwiftAccessOptions.accessibleWhenUnlocked.value, accessValue!)
   }
 
   // MARK: - Get

+ 3 - 3
KeychainSwiftTests/SynchronizableTests.swift

@@ -70,12 +70,12 @@ class SynchronizableTests: XCTestCase {
   
   func testGet() {
     obj.synchronizable = true
-    obj.get("key 1")
+    _ = obj.get("key 1")
     XCTAssertEqual(kSecAttrSynchronizableAny, obj.lastQueryParameters?["sync"])
   }
   
   func testGet_doNotSetSynchronizable() {
-    obj.get("key 1")
+    _ = obj.get("key 1")
     XCTAssertNil(obj.lastQueryParameters?["sync"])
   }
   
@@ -104,4 +104,4 @@ class SynchronizableTests: XCTestCase {
     obj.clear()
     XCTAssertNil(obj.lastQueryParameters?["sync"])
   }
-}
+}