Browse Source

feat: allKeys function

Lucas Paim 6 years ago
parent
commit
dd1b0e4462
2 changed files with 32 additions and 0 deletions
  1. 26 0
      Sources/KeychainSwift.swift
  2. 6 0
      Sources/TegKeychainConstants.swift

+ 26 - 0
Sources/KeychainSwift.swift

@@ -232,6 +232,32 @@ open class KeychainSwift {
     return deleteNoLock(key)
     return deleteNoLock(key)
   }
   }
   
   
+    /**
+     Return all keys from keychain
+     
+     - returns: An string array with all keys on keychain
+     */
+    open func allKeys() -> [String] {
+        var query: [String: Any] = [
+            KeychainSwiftConstants.klass : kSecClassGenericPassword,
+            KeychainSwiftConstants.returnData : true,
+            KeychainSwiftConstants.returnAttributes: true,
+            KeychainSwiftConstants.returnReference: true,
+            KeychainSwiftConstants.matchLimit: KeychainSwiftConstants.secMatchLimitAll
+        ]
+        query = addAccessGroupWhenPresent(query)
+        query = addSynchronizableIfRequired(query, addingItems: false)
+        
+        var result: AnyObject?
+        let lastResultCode = withUnsafeMutablePointer(to: &result) {
+            SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
+        }
+        if lastResultCode == noErr {
+            return (result as? [[String: Any]])?.compactMap { $0[KeychainSwiftConstants.attrAccount] as? String } ?? []
+        }
+        return []
+    }
+    
   /**
   /**
    
    
   Same as `delete` but is only accessed internally, since it is not thread safe.
   Same as `delete` but is only accessed internally, since it is not thread safe.

+ 6 - 0
Sources/TegKeychainConstants.swift

@@ -34,6 +34,12 @@ public struct KeychainSwiftConstants {
   /// Used for returning a reference to the data from the keychain
   /// Used for returning a reference to the data from the keychain
   public static var returnReference: String { return toString(kSecReturnPersistentRef) }
   public static var returnReference: String { return toString(kSecReturnPersistentRef) }
   
   
+  /// A key whose value is a Boolean indicating whether or not to return item attributes
+  public static var returnAttributes : String { return toString(kSecReturnAttributes) }
+    
+  /// A value that corresponds to matching an unlimited number of items
+  public static var secMatchLimitAll : String { return toString(kSecMatchLimitAll) }
+    
   static func toString(_ value: CFString) -> String {
   static func toString(_ value: CFString) -> String {
     return value as String
     return value as String
   }
   }