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.
Related
I am trying to build a text recognizer app in iOS with the Firebase ML Kit. I have tried following some tutorials, but no luck. I keep getting the following error at the line indicated (return self.result):
Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
I am still very new to Swift/xcode and firebase so any help would be greatly appreciated!
var result: VisionText!
var textRecognizer: VisionTextRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let vision = Vision.vision()
textRecognizer = vision.cloudTextRecognizer()
imageResult.image = UIImage(named: "sampletext")
print(textRecognition(image: imageResult.image!))
textResult.text += scantext
}
func textRecognition(image: UIImage) -> VisionText{
let visionImage = VisionImage(image: image)
textRecognizer.process(visionImage) { (result, error) in guard error == nil, case self.result = result else {
print("oops")
return
}
print("oops")
}
return self.result \\ ERROR
}
EDIT
I made sure to implement a correct way to unwrap an optional. My problem is that the Firebase MLVision process does not return anything, the result is nil. Not sure if I am going about the method incorrectly. Here is my updated code with some small changes.
var scannedresult: VisionText!
var textRecognizer: VisionTextRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let vision = Vision.vision()
textRecognizer = vision.cloudTextRecognizer()
imageResult.image = UIImage(named: "sampletext")
print("oops")
print(textRecognition(image: imageResult.image!))
// textResult.text += scannedresult.text
}
func textRecognition(image: UIImage) {
let visionImage = VisionImage(image: image)
textRecognizer.process(visionImage) { (result, error) in guard error == nil, let result = result else { print("oops")
return }
self.scannedresult = result
}
}
"Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value"
^This error occurs when you are trying to access a value for an option variable, and the value is nil. You have to unwrap it safely. There are five ways to unwrap an optional. This is my preferred way:
guard let result = self.result else { return }
return result
the guard statement will cause your code to skip over the next lines in the block if there is no value, or NIL, in the result.
Here is a quick read on all the ways to unwwrap your optionals w/ examples
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")
}
When I try to read data in HealthKit I get an error telling me that the application crashed because of
fatal error: unexpectedly found nil while unwrapping an Optional value
I understand that I am trying to unwrap an optional that is nil, but when I try to use optionals I get an error telling me to force unwrap it.
Here is some of the code that I am using:
import Foundation
import HealthKit
import UIKit
class HealthManager {
let healthKitStore = HKHealthStore()
func authorizeHealthKit(completion: ((success: Bool, error: NSError) -> Void)!) {
// Set the Data to be read from the HealthKit Store
let healthKitTypesToRead: Set<HKObjectType> = [(HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned))!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierFlightsClimbed)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierNikeFuel)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!]
// Check if HealthKit is available
if !HKHealthStore.isHealthDataAvailable() {
let error = NSError(domain: "com.MyCompany.appName", code: 2, userInfo: [NSLocalizedDescriptionKey: "HealthKit is not available on this device"])
if completion != nil {
completion?(success: false, error: error)
}
return;
}
// Request HealthKit Access
self.healthKitStore.requestAuthorizationToShareTypes(nil, readTypes: healthKitTypesToRead) {
(success, error) -> Void in
if completion != nil {
completion?(success: true, error: error!)
}
}
}
}
Also, if I try to remove the bang operator(!) I get an error saying that:
Value of optional type 'HKQuantityType?' not unwrapped; did you mean to use '!'?
Since quantityTypeForIdentifier returns HKQuantityType?, then force unwrapping it can result in unwrapping a nil value, as you know. You have to check for nil, for example in the form:
if let objectType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierFlightsClimbed) {
// Add objectType to set
}
I realized that when I was requesting HealthKit access this piece of code was returning nil:
if completion != nil {
completion?(success: true, error: error!)
}
It turns out that the error was actually nil and I was force unwrapping the nil. As a result, I changed the code to:
if error != nil && completion != nil {
completion?(success: true, error: error!)
}
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")
}
This is my code here found the fatal error.,and it shows the
EXC_BAD_INSTRUCTION(code=EXC_i386_INVOP,subcode=0*0)
let email: NSString = NSUserDefaults.standardUserDefaults().objectForKey("fb_email")! as NSString
It seems like NSUserDefaults.standardUserDefaults().objectForKey("fb_email") is nil. When you try to unwrap it with !, a fatal error occurs.
Try this:
if let object = NSUserDefaults.standardUserDefaults().objectForKey("fb_email") {
// do sth. with object
} else {
// error
}