This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
I'm trying to send a saved string to the apple watch with WCsession methode. But when I do this I get an error in swift 2.3: fatal error: unexpectedly found nil while unwrapping an optional value !!
func Reloadip() {
let ip = nsdefauts.object(forKey: saved)
let requestValues = ["send" : "A" , "IP" : ip as! String ]
print(requestValues)
if(WCSession.isSupported()){
session!.sendMessage(requestValues, replyHandler: nil, errorHandler: nil)
print("sended ip")
}
}
the error is made at the "ip as! String line" how can I fix this. ?
regards Quinn
You should use more safe code instead
func Reloadip() {
guard let ip = nsdefauts.objectForKey(saved) as? String else {
print("there is no saved ip")
return
}
let requestValues = ["send" : "A" , "IP" : ip]
print(requestValues)
if(WCSession.isSupported()){
session?.sendMessage(requestValues, replyHandler: nil, errorHandler: nil)
print("sended ip")
}
}
Related
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 2 years ago.
im having this problem: Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
is there any way to solve it?
this is my code:
let ref = Database.database().reference()
ref.child("ChildA").child("Title").observeSingleEvent(of: .value, with: { DataSnapshot in
print(DataSnapshot) // replace this with textLabel or other item
let m = DataSnapshot.value as? String
self.TitleA.text = m //Error in this line
})
Replace:
self.TitleA.text = m
With this:
self.TitleA?.text = m ?? ""
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 3 years ago.
func doGetLocalDataUser() -> logInResponse {
var localData : logInResponse? = nil
if let userData = UserDefaults.standard
.data(forKey: ConstantStrings.KEY_USER_LOGIN_DATA),let user = try? JSONDecoder()
.decode(logInResponse.self ,from: userData){
localData = user
}
return localData!
}
I would change the method to this:
func doGetLocalDataUser() -> logInResponse? {
guard let userData = UserDefaults.standard.data(forKey: ConstantStrings.KEY_USER_LOGIN_DATA), let user = try? JSONDecoder().decode(logInResponse.self ,from: userData) else {
return nil
}
return user
}
Keep in mind JSON decoding can fail (maybe has wrong format), therefore user will be nil, and this method can return nil
localData is nil, so you are force unwrapping localData (as a logInResponse) illegally.
If your optional chaining finds nil at any point (for example your userData doesn't exist in UserDefaults / has the wrong type) then it won't execute.
You are declaring this doGetLocalDataUser() function to return a non optional logInResponse type and force unwrapping a nil value to try and retrieve one. Best practice is to avoid the force unwrap "bang" operator "!" because it can lead to fatal errors like this.
Simple solution is to change your method to return an optional logInResponse? type, and eliminate the bang operator:
func doGetLocalDataUser() -> logInResponse? {
if let userData = UserDefaults.standard.data(forKey: ConstantStrings.KEY_USER_LOGIN_DATA), let user = try? JSONDecoder().decode(logInResponse.self ,from: userData){
return user
} else {
return nil
}
}
I'm trying to determine whether or not a user is entering a proper email address into a UITextField . I'm using this code but am getting the following error message.
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch) // I'm getting the error message here.
let result = range != nil ? true : false
return result
}
#IBAction func logIn(sender: AnyObject) {
let validLogin = isValidEmail(testStr: field.text!)
if validLogin {
print("User entered valid input")
} else {
print("Invalid email address")
}
}
This is the error message I'm getting: "Value of type 'String' has no member 'rangeOfString'"
I think this is because I don't have RegExKitLite installed but I'm not 100% sure. Even so, I tried installing the kit but I couldn't figure out how. I downloaded the file but I can't figure out how to add it in Xcode.
If you are using Swift 3 or later, the lines:
let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
let result = range != nil ? true : false
return result
needs to be:
let range = testStr.range(of: emailRegEx, options: [ .regularExpression ])
return range != nil
None of this needs a third party library.
You probably also want to make sure the whole string matches so you should add ^ to the start of the regular expression and add $ to the end.
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 6 years ago.
I got access error('fatal error: unexpectedly found nil while unwrapping an Optional value') when print variable p02. According to the error message, I still cannot understand the reason.
var p02:Person! = nil
var p03:Person? = nil
if (p02==nil)
{
print("p02 is nil")
}
if (p03==nil)
{
print("p03 is nil")
}
print(p03)
print(p02)
Anyone know why,
Thanks
cause it always tries to print p02 and p03 even if they are nil
try this
var p02:Person! = nil
var p03:Person? = nil
if (p02==nil)
{
print("p02 is nil")
}else{
print(p02)
}
if (p03==nil)
{
print("p03 is nil")
}else{
print(p03)
}
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 1 year ago.
I am programming a small social network app for a community in Swift.
I got the error: fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) when I try to change views with self.presentViewController(FeedViewController(), animated: true, completion: nil). This line of code only executes if the user is allowed access to the second page.
Here is the full code:
#IBAction func loginButtonPressed(sender: AnyObject) {
if passwordTextField.text == "" || nameTextField.text == "" {
Global.showAlert("Erreur", message:"Nom d'utilisateur ou mot de passe invalide!", view:self)
} else {
PFUser.logInWithUsernameInBackground(nameTextField.text, password:passwordTextField.text) {
(user: PFUser!, error: NSError!) -> Void in
if user != nil {
} else {
// The login failed. Check error to see why.
//var err = error.userInfo["error"] as NSString
Global.showAlert("Erreur", message:"Nom d'utilisateur ou mot de passe invalide!", view:self)
}
}
Based off be comments above it sounds like your app is crashing after the login. If that's the case:
Try changing user!=nil to error == nil
UPDATE
Check class permissions