Getting Optional( ) when trying to get value from KeyChain
You get the Optional("")
because the optional value is not unwrapped. You need to put a !
after the object and you won't get the Optional("")
bit any more. I would show you the code but you haven't shown us the print()
statement. I made some sample ones below that I think would replicate the problem, though I haven't tried them.
var value:String?
value = "Hello, World"
print("The Value Is \(value)") // Prints "The Value Is Optional(Hello, World)"
print("The Value Is \(value!)")// Prints "The Value Is Hello, World"
Im hoping this answers your question or at least points you in the right direction, just ask if you need more information or a better example.
Get rid of these Optional values
You're overusing !
. You don't need them. Try to learn more about implicitly unwrapped optionals, optionals, ... Your code is a mess (no offense, everybody's learning).
Back to your optional problem, it's caused by this line:
let username : String! = String(NSString(data: NsDataUsername!, encoding: NSUTF8StringEncoding))
convenience init?(data: NSData, encoding: UInt)
- inner part utilizes failable initializer, so, NSString?
is the result. Then initialization of String
with optional NSString?
produces optional as well. But, it has no sense at all do it in this way.
First part - remove optional
Utilizing new guard
:
guard let loadedPassword = NSString(data: passwordData, encoding: NSUTF8StringEncoding) else {
fatalError("Ooops")
}
loadedPassword
contains NSString
(not NSString?
) now.
Second part - NSString
-> String
You did probably read (if not, read) Strings and Characters about bridging, ... If you can freely exchange NSString
with String
, you can think that you're done:
var dict = [String:String]()
dict["password"] = loadedPassword
Nope. It produces following error:
NSString
is not implicitly convertible toString
; did you mean to
use 'as' to explicitly convert?
Slight change and now you're done:
var dict = [String:String]()
dict["password"] = loadedPassword as String
Complete example
let password = "Hallo"
guard let passwordData = password.dataUsingEncoding(NSUTF8StringEncoding) else {
fatalError("Ooops")
}
// save/load to/from keychain
guard let loadedPassword = NSString(data: passwordData, encoding: NSUTF8StringEncoding) else {
fatalError("Ooops")
}
var dict = [String:String]()
dict["password"] = loadedPassword as String
print(dict) // "[password: Hallo]\n"
Save and retrieve value via KeyChain
Well, I just used out source etc and made my self nice helper :
Enjoy!
class func save(key: String, data: NSData) {
let query = [
kSecClass as String : kSecClassGenericPassword as String,
kSecAttrAccount as String : key,
kSecValueData as String : data ]
SecItemDelete(query as CFDictionaryRef)
let status: OSStatus = SecItemAdd(query as CFDictionaryRef, nil)
}
class func load(key: String) -> NSData? {
let query = [
kSecClass as String : kSecClassGenericPassword,
kSecAttrAccount as String : key,
kSecReturnData as String : kCFBooleanTrue,
kSecMatchLimit as String : kSecMatchLimitOne ]
var dataTypeRef :Unmanaged<AnyObject>?
let status: OSStatus = SecItemCopyMatching(query, &dataTypeRef)
if status == noErr {
return (dataTypeRef!.takeRetainedValue() as! NSData)
} else {
return nil
}
}
class func stringToNSDATA(string : String)->NSData
{
let _Data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)
return _Data!
}
class func NSDATAtoString(data: NSData)->String
{
var returned_string : String = NSString(data: data, encoding: NSUTF8StringEncoding)! as String
return returned_string
}
class func intToNSDATA(r_Integer : Int)->NSData
{
var SavedInt: Int = r_Integer
let _Data = NSData(bytes: &SavedInt, length: sizeof(Int))
return _Data
}
class func NSDATAtoInteger(_Data : NSData) -> Int
{
var RecievedValue : Int = 0
_Data.getBytes(&RecievedValue, length: sizeof(Int))
return RecievedValue
}
class func CreateUniqueID() -> String
{
var uuid: CFUUIDRef = CFUUIDCreate(nil)
var cfStr:CFString = CFUUIDCreateString(nil, uuid)
var nsTypeString = cfStr as NSString
var swiftString:String = nsTypeString as String
return swiftString
}
//EXAMPLES
//
// //Save And Parse Int
// var Int_Data = KeyChain.intToNSDATA(555)
// KeyChain.save("MAMA", data: Int_Data)
// var RecievedDataAfterSave = KeyChain.load("MAMA")
// var NSDataTooInt = KeyChain.NSDATAtoInteger(RecievedDataAfterSave!)
// println(NSDataTooInt)
//
//
// //Save And Parse String
// var string_Data = KeyChain.stringToNSDATA("MANIAK")
// KeyChain.save("ZAHAL", data: string_Data)
// var RecievedDataStringAfterSave = KeyChain.load("ZAHAL")
// var NSDATAtoString = KeyChain.NSDATAtoString(RecievedDataStringAfterSave!)
// println(NSDATAtoString)
Swift + Locksmith: Not getting stored Keychain Value
Looks like you're pulling your "password" string out of the dictionary incorrectly. Don't use the .stringValue function in this case. Change this line:
if let passwordSaved = dictionary!["password"]?.stringValue {
to
if let passwordSaved = dictionary!["password"] as? String {
Getting value of NSCoding into string - KeychainWrapper
Try as,
let userOptions = (KeychainWrapper.standard.object(forKey: "userOptions").unsafelyUnwrapped as! [[String]]).joined().joined(separator: " ") )
Related Topics
How to Simulate Mouse Click from MAC App to Other Application
Process Array in Parallel Using Gcd
How to Find Actual Swiftui API Documentation (And Not Just the Developer Documentation)
How to Use List Type with Codable? (Realmswift)
How to Capture Depth Data from Camera in iOS 11 and Swift 4
Inconsistent Scenekit Framerate
Ios8 Custom Keyboard - Copy & Paste to Uipasteboard
How Constant Is the Firebase Anonymous Id
Add Animations to Foreach Loop Elements (Swiftui)
How to Tell If a Node Is on the Screen Spritekit Swift
Swift Update Label (With HTML Content) Takes 1Min
How Do People Deal with Iterating a Swift Struct Value-Type Property
How to Use Sf Rounded Font in Swiftui
Check If Variable Is an Optional, and What Type It Wraps
Private Var Is Accessible from Outside the Class
Does Swift Have a Null Coalescing Operator and If Not, What Is an Example of a Custom Operator