i am trying to compare in login form password value with UserDefault value . but an error occur that bool operation cant be perform there.
Please can any one help me compare both values.
How can i compare these values?
if let savedPassword = UserDefaults.standard.string(forKey: "password") {
let enteredPassword = textField?.text
if savedPassword == enteredPassword {
// Do stuff.
}
}
else {
// Failure.
}
I wouldn't recommend storing passwords in plain text in UserDefaults.
There are a number of tutorials on this topic available, for example https://medium.com/ios-os-x-development/securing-user-data-with-keychain-for-ios-e720e0f9a8e2
Please use the below code snippet
if passwordField.text == UserDefaults.standard.string(forKey:"password"){
print("Same Password")
}
Thanks
You have to specify your object type
if UserDefaults.standard.string(forKey: "password") == passwordLabel.text {
// ...
}
I think you should cast your result from Any to String from User Defaults
if let yourString = UserDefaults.standard.string(forKey: "yourString"), yourString == passwordTextField.text {
// do something here
}
Related
I was confused.
it's because, my control flow is not work as should be.
I think, it's just basic logic. But, oddly enough, my control flow not as what I want to be.
This is my code.
which is, isLogin() method, have this code:
the oddly is why the control flow always go to if statement, even the user not yet to login.
NB: If user not already to login, the current view must be present LoginViewController.
anyone can to explain this problem? Thank you
Userdfaults returns nil when it has no value.
Add nil instead of empty quotes:-
if UserDefaults.standard.string(forKey: "token") != nil {
return true
} else {
return false
}
UserDefaults returns nil if there is no value for "token"
so check that value not equal to nil
func isLogin()->Bool{
let defaults = UserDefaults.standard
guard let token = defaults.string(forKey: "token") else{
return false
}
return true
}
string(forKey: "token") is optional because can return and nil when it has no value, 'isEmpty' method checks when the string is empty or not!
func isLogin() -> Bool {
let token = UserDefaults.standard.string(forKey: "token")
return token != nil && !token!.isEmpty
}
I'm having my string declared as,
var firstName = String()
and I'm assigning value from parsed JSON content like,
firstName = json["first_name"].stringValue
But sometimes, there might be empty values in the JSON response and the app is crashing, I read about guard statement and if statement to check empty values, but that requires the declaration format to be changed, couldn't find a right way to handle this error without changing the declaration format.
since I have declared all the variables in my app with similar formats, changing that requires time, I'm in the verge of uploading my app, this is my first swift app, if my declaration format is wrong please answer why it is, can someone help me out of this?
Code as of Swift 4:
Keep in mind that when you are using ".stringValue", it is almost the same as using a "!" which will force a crash on nil.
if let firstName = json["first_name"]as? String {
//do stuff like
self.firstName = firstName
}
This will unwrap it to where you can get at the value if it isn't null and can be a string.
Guard let's are really good for this though as you can account for it in the beginning and you can assume that it is not optional for the entire scope.
guard let firstName = json["first_name"]as? String else {return}
self.firstName = firstName
In addition, you could always check for nulls in one line and assign a default value if a nil value occurs.
self.firstName = (json["first_name"]as? String) ?? "Default String"
You can use next statement:
guard let firstName = json["first_name"].stringValue else { // Do sth if nil }
// Do sth if not nil
Or you could use statement, which you wrote, but you should check variable
firstName like this:
guard firstName != nil else { // Do sth if nil }
// Do sth if not nil
Or
if firstName != nil {
// Do sth if not nil
}
You can use guard statement also,
guard let firstName = json["first_name"] else {
print("FirstName is Empty")
return
}
or you can check with if also,
if let firstName = json["first_name"] {
//Your code goes here
}
You can do that the following way:
if let dictionary = json {
if let fName = dictionary["first_name"] {
firstName = fName as? String
}
}
I guest you use SwiftyJSON. The function stringValue always return String object. It's impossible to be nil. It sounds like the response data which is not valid JSON format, so it crashed.
My snippet codes.
// Alarmofire + SwiftyJSON
let request: DataRequest = ...//< Configure Alarmofire DataRequest
request.response() { (resp) in
if let error = resp.error {
// TODO: Error handle
return
}
if (response.data == nil) {
// TODO: error handle for empty data?
return
}
assert(response.data != nil, "In this place, the `data` MUST not be nil.")
let json = try? JSON(data: response.data!)
if (json == nil) {
// TODO: Error handle for invalid JSON format.
// If json is nil, then `json["first_name"]` will lead to crash.
return
}
// TODO: parse json object
let firstNameStr = json["first_name"].stringValue
}
I've received the following compiler error
"value of optional type 'String?' not unwrapped; did you mean to use
'!'or '?'?"
This is my code
#IBAction func registerButtonTapped(sender: AnyObject)
{
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
let userConfirmPassword = confirmPasswordTextField.text;
// check for empty fields
if userEmail.isEmpty || userPassword.isEmpty || userConfirmPassword.isEmpty
{
//Display alert message
displayMyAlertMessage("All fields are required");
return;
}
The error shows at line:
if userEmail.isEmpty || userPassword.isEmpty || userConfirmPassword.isEmpty
Brush up on Swift basics, check out the Optional Chaining guide for help with this kind of problem.
But in general...
Any textField.text property is an optional, meaning it could be nil.
Therefore your variables like userEmail are optional as well, and could be nil.
You can't call a property or method on an optional variable without first unwrapping it. There's two ways to do this.
userEmail!.isEmpty says that you guarantee that userEmail is not nil
userEmail?.isEmpty says maybe you're not sure and only check isEmpty is userEmail happens to not be nil
You can also unwrap an optional using if let:
if let userEmail = userEmail, userPassword = userPassword, userConfirmPassword = userConfirmPassword where userEmail.isEmpty || userPassword.isEmpty || userConfirmPassword.isEmpty {
//do stuff
}
That's the best short explanation I can give. Study, learn, code.
You have not unwrapped the text fields in your code.
The system does not know if there is text present in your textfield. So, when you say:
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
let userConfirmPassword = confirmPasswordTextField.text;
The values in userEmail, userPassword and userConfirmPassword are Optional Strings. To force unwrap them, you can do the following:
let userEmail = userEmailTextField.text!;
let userPassword = userPasswordTextField.text!;
let userConfirmPassword = confirmPasswordTextField.text!;
But, bear in mind that if the user does not enter any value in the textfields, you will get a crash.
Instead of force unwrapping, you should use safe unwrap, like this:
if let userEmail = userEmailTextField.text {
//Do something
} else {
//Handle case where input is nil
}
You can read more about optionals and their unwrapping here.
In my app I have a simple user base that looks like this:
What I'm trying to do is to simply fetch this list once, to check wether a username is valid when a new user signs up with a new username.
The thing is that the only ways I found to retrieve data utilize some sort of observer methods, which are not good for me.
The logic I'm trying to achieve (with the retrieving method that doesn't work) :
// When user tries to sign up with a new username
let username = nicknameField.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
self.usersRef.observeEventType(.Value) { (snapshot: FIRDataSnapshot) in
let dict = snapshot.value as! NSDictionary
for val in dict.allValues {
if username == val as! String {
// Present alert
return
}
}
}
self.usersRef.child(username).setValue(username) { (error, dbRef) in
if error == nil {
// Continue
}
}
How can I simply just fetch the list of users once?
Thanks in advance!
I had to change the observeEventType method to observeSignleEventOfType.
I have also updated my code to make it work (regardless):
self.usersRef.observeSingleEventOfType(.Value) { (snapshot: FIRDataSnapshot) in
let dict = snapshot.value as! NSDictionary
for val in dict.allValues {
if username == val as! String {
// Present alert
return
}
else {
self.usersRef.child(username).setValue(username) { (error, dbRef) in
if error == nil {
// Continue
}
}
}
Update: I've tried changing setValue to setObject, and the same error occurred.Upon further investigation with breakpoints and the LLDB, they are nil before the controller is even presented. I'm not saving them right.
I'm trying to simply save a couple of strings of text, and display them on another view using Swift. I'm not sure why I'm having such a hard time. Here is how I'm trying to accomplish this:
VC1
#IBAction func registerTapped(sender : AnyObject)
// Save the login information
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(username.text, forKey: "username")
defaults.setValue(password.text, forKey: "password")
if firstName.text.isEmpty == false {
defaults.setValue(firstName.text, forKey: "firstname")
}
if lastName.text.isEmpty == false {
defaults.setValue(lastName.text, forKey: "lastname")
}
let profileView = ProfileViewController()
self.presentViewController(profileView, animated: true, completion: nil)
}
}
Cool. That looks like the correct way to save strings in UITextFields based upon my research. So, I open up VC2 and try to load the saved text into the new UITextField's, like so:
override func viewDidLoad() {
super.viewDidLoad()
let defaults = NSUserDefaults.standardUserDefaults()
username.text = defaults.stringForKey("username")
password.text = defaults.stringForKey("password")
if let first = defaults.stringForKey("firstname")
{
firstName.text = first
}
if let last = defaults.stringForKey("lastname") {
lastName.text = last
}
}
I get the crash fatal error: unexpectedly found nil while unwrapping an Optional value. I've been digging through tutorials for hours and can't for the life of me figure out what I am doing wrong.
Is it because it an an optional? This is my LLDB output:
Your issue has nothing to do NSUserDefaults, whats nil are your labels username, password, etc. in your second controller.
You should add a segue to your button (the one with registerTapped) to show the second controller and remove the last two lines in registerTapped.
Break your code into steps and debug each one. Your code would crash if your outlet is nil or if the key/value pair doesn't exist. Check that both username and password (The text fields) are not nil, as well as that the defaults results aren't nil:
var text: String?
text = defaults.stringForKey("username")
if let text = text
{
if let username = username
{
username.text = text
}
else
{
println("username field is nil!")
}
}
else
{
println("defaults stringForKey("username") = nil!")
}
text = defaults.stringForKey("password")
if let text = text
{
if let password = password
{
password.text = text
}
else
{
println("password field is nil!")
}
}
else
{
println("defaults stringForKey("password") = nil!")
}