Created
October 3, 2018 02:48
-
-
Save quocnb/1a2e4b7cdddca8aae2cada40eb7eb27b to your computer and use it in GitHub Desktop.
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
public struct URLCredentialHelper { | |
enum URLCredentialError { | |
static let invalidUrl = NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: nil) | |
} | |
static func store(user: String, password: String, url: String) throws { | |
let protectionSpace = try createProtectionSpace(for: url) | |
let credentital = URLCredential(user: user, password: password, persistence: .permanent) | |
URLCredentialStorage.shared.set(credentital, for: protectionSpace) | |
} | |
static func getPassword(of user: String, at url: String) throws -> String? { | |
let protectionSpace = try createProtectionSpace(for: url) | |
let credentitals = URLCredentialStorage.shared.credentials(for: protectionSpace) | |
return credentitals?[user]?.password | |
} | |
static func deleteCredential(of user: String, at url: String) throws { | |
let protectionSpace = try createProtectionSpace(for: url) | |
let credentitals = URLCredentialStorage.shared.credentials(for: protectionSpace) | |
guard let credentialOfUser = credentitals?[user] else { | |
return | |
} | |
URLCredentialStorage.shared.remove(credentialOfUser, for: protectionSpace) | |
} | |
private static func createProtectionSpace(for urlString: String) throws -> URLProtectionSpace { | |
guard let url = URL(string: urlString), let host = url.host else { | |
throw URLCredentialError.invalidUrl | |
} | |
return URLProtectionSpace( | |
host: host, | |
port: url.port ?? 80, | |
protocol: url.scheme, | |
realm: nil, | |
authenticationMethod: NSURLAuthenticationMethodHTTPDigest | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment