I have a core data app with some items and imageviews. Now i would like to delete a picked photo from my imageview1 field.
imageView1.image = nil
and it works and my imageview1 ist empty, but when i save the record my app is crashing with the error:
fatal error: unexpectedly found nil while unwrapping an Optional value.
Whats the problem? Is it possible to "reset" the imageview1.image?
The error itself tells that while unwrapping an optional value, value found was nil. You need to first check if optional value is nil using if let or guard and unwrap(!) only when they are not nil.
If let image = imageView.image {
Item!.image =UIImagePNGRepresentation(imageView1.image!)"
} else {
Item.image = image(named: "placeholderimage")
}
Related
I have hooked to Selection changed event of NSTableView.I need to display the selected image in the imageview
func tableViewSelectionDidChange(_ notification: Notification)
{
let table = notification.object as! NSTableView
print(fileArray[table.selectedRow].path);
img_view.image=NSImage(named: NSImage.Name(rawValue: fileArray[table.selectedRow].path))
}
The console prints
/Users/myname/Downloads/435_v9_bc.jpg
But the imageview does not display the image.
Update 1:
print(fileArray[table.selectedRow].path);
img_view.image=NSImage(byReferencing: URL(string: fileArray[table.selectedRow].path)!)
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Console still prints
/Users/myname/Downloads/123_1 (1).jpeg
URL(string: is the wrong API, for file system paths you have to use URL(fileURLWithPath.
img_view.image = NSImage(byReferencing: URL(fileURLWithPath: fileArray[table.selectedRow].path))
However fileArray[table.selectedRow] seems to be already an URL so there is a still easier way
img_view.image = NSImage(contentsOf: fileArray[table.selectedRow])
This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 4 years ago.
I have put a full-screen size invisible button behind of all objects(like textfield, picker.. ) to close opened keyboard. I call below function when the button is clicked:
func hideKeyboard() {
for view in self.contentViewOutlet.subviews {
if let tField = view as? UITextField {
tField.resignFirstResponder()
}
}
}
but I get this error after I click the button:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
I roughly know what does it mean but I couldn't write a solution. (Actually, this hideKeyboard() function was working fine. It starts to give an error after I add UIPickerView)
Your contentViewOutlet is an Outlet so it might be nil, but it's implicitly unwrapped. And you get this error because when you tap a button, this object is nil. To avoid the crash, change your code to
func hideKeyboard() {
guard let contentView = self.contentViewOutlet else { return }
for view in contentView.subviews {
if let tField = view as? UITextField {
tField.resignFirstResponder()
}
}
}
After that, your method won't do anything if contentViewOutlet is nil.
Having an app where I type username, pick a picture from imagePickerController and all that data is saved to core data and retrieved to tableview cell and is working fine, however if I don't choose picture app is crashing with log "unexpectedly found nil while unwrapping an Optional value", I forgot how to do that, can't remember in what project I solved that.
let imageData = NSData(data: UIImageJPEGRepresentation(photoImageView.image!, 1.0)!)
newUser.setValue(imageData, forKey: "image")
Something like if image data != nil {
} ??
Try if let image = photoImageView.image {//use the image}. This will unwrap the optional in a safe way.
Be careful when you use the ! operator, you are basically guaranteeing the thing will never be nil. Use the if let statement or ? operator unless there is absolutely no way that the variable in question could be nil.
solved with this
if photoImageView == nil {
let imageData = NSData(data: UIImageJPEGRepresentation(photoImageView.image!, 1.0)!)
newUser.setValue(imageData, forKey: "image")
}
Trying to implement this raywenderlich tutiorial in swift , but unfortunately I am
fatal error: unexpectedly found nil while unwrapping an Optional value
on line
let acceleration :CMAcceleration = self.motionManager!.accelerometerData.acceleration
Can any body please help why its occuring
please down scene file from here
self.motionManager is nil and you try to unwrap a nil value.Always unwrap optional values by checking for nil with optional binding or use optional chaining.
if let motionManager = self.motionManager {
if let accelerometerData = motionManager.accelerometerData {
let acceleration :CMAcceleration = accelerometerData.acceleration
}
}
else {
print("motion manager is nil")
}
You should check your code if you have intialized motionManager or not.
EDIT
I have checked documentation
Returns the latest sample of accelerometer data, or nil if none is
available.
*/
var accelerometerData: CMAccelerometerData! { get }
So you need to also check nil for accelerometerData.It can be nil and it is Implicitly wrapped optional so it will crash when data not available.
This bit of code has been working for me ever since I wrote it, yet today it decided to quit working on me. I've been trying to resolve the issue the majority of the day, and it's slowly driving me crazy. I keep getting a "fatal error: unexpectedly found nil while unwrapping an Optional value" error. I understand what it means, but I can't seem to fix it. I found this thread - "unexpectedly found nil while unwrapping an Optional value" when retriveing PFFile from Parse.com - and tried the solution, but it did not work. Here is my code:
if let userImageFile: AnyObject = content["imageFile"] as? PFFile {
println("Here is your userImageFile: \(userImageFile)")
userImageFile.getDataInBackgroundWithBlock { (imageData:NSData!, error:NSError!) -> Void in
if error == nil
{
var contentImage = UIImage(data: imageData)
self.feedView.image = contentImage
}
}
}
I know that the userImageFile is not nil, because the print line I have put in before getDataInBackgroundWithBlock correctly prints out the PFFile i'm trying to access from my Parse data browser. I just don't understand how it can work for a week and then suddenly stop working. If someone could help me, I would really appreciate it. Thanks!
ANSWER
So after banging my head into my desk for many hours, I finally said screw it and deleted my code, only to re-write it and have it work again...This is now working code, but I've also updated it a bit with the suggestions of the post below.
if let imageFile: AnyObject = content["imageFile"] as? PFFile {
imageFile.getDataInBackgroundWithBlock({ (imageData:NSData!, error:NSError!) -> Void in
if let imageData = imageData
{
dispatch_async(dispatch_get_main_queue())
{
var contentImage = UIImage(data: imageData)
self.feedView.image = contentImage
}
}
else
{
//Do something else
}
})
}
Even if userImageFile is not nil, you are making the assumption that imageData passed to the closure is not nil. I would check that the image actually exists at server side, and modify your closure code as follows:
if let imageData = imageData {
dispatch_async(dispatch_get_main_queue()) {
var contentImage = UIImage(data: imageData)
self.feedView.image = contentImage
}
} else {
// Something happened
}
Remember that an explicitly unwrapped optional can technically be nil - it's still an optional, but you are instructing the compiler to consider it as a non optional (i.e. automatically unwrap).
Also note that you are modifying a UI component from a thread that is probably not the main. It's better to enclose it in a dispatch_async on the main thread.