Last active
November 25, 2022 08:24
-
-
Save soffes/0f123d1117eaed885d3a40890ccaf070 to your computer and use it in GitHub Desktop.
Easily access Shared Web Credentials
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Security | |
struct SharedWebCredentials { | |
// MARK: - Types | |
struct Credential { | |
let domain: String | |
let account: String | |
let password: String | |
init?(dictionary: NSDictionary) { | |
let dict = dictionary as Dictionary | |
guard let domain = dict[kSecAttrServer] as? String, | |
account = dict[kSecAttrAccount] as? String, | |
password = dict[kSecSharedPassword] as? String | |
else { return nil } | |
self.domain = domain | |
self.account = account | |
self.password = password | |
} | |
} | |
// MARK: - Accessing Credentials | |
static func get(domain domain: String? = nil, account: String? = nil, completion: (credential: Credential?, error: CFError?) -> Void) { | |
SecRequestSharedWebCredential(domain, account) { array, error in | |
let credential: Credential? | |
if let array = array as Array?, dictionary = array.first as? NSDictionary { | |
credential = Credential(dictionary: dictionary) | |
} else { | |
credential = nil | |
} | |
completion(credential: credential, error: error) | |
} | |
} | |
static func add(domain domain: String, account: String, password: String, completion: ((error: CFError?) -> Void)? = nil) { | |
SecAddSharedWebCredential(domain, account, password) { error in | |
completion?(error: error) | |
} | |
} | |
static func remove(domain domain: String, account: String, completion: ((error: CFError?) -> Void)? = nil) { | |
SecAddSharedWebCredential(domain, account, nil) { error in | |
completion?(error: error) | |
} | |
} | |
static func generatePassword() -> String? { | |
return SecCreateSharedWebCredentialPassword() as String? | |
} | |
} |
Haven't used this in years, sorry.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update:
It works well on simulator regardless of the iOS version, but fails on real device with " failed to approve" error.
https://developer.apple.com/forums/thread/19441
https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_developer_associated-domains