CoreData unexpectedly found nil while unwrapping an Optional value - swift

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")
}

Related

optional convenience init with multiple attempts to initialise

I have a factory method on UIImage that looks in multiple bundles for the image as the projects I'm working on are sometimes broken up.
Key is an enum for type safety around various properties.
public extension UIImage {
static func with(_ key: Key, in bundle: Bundle? = nil) -> UIImage? {
if let image = UIImage(key, in: bundle) { return image }
if let image = UIImage(key, in: .main) { return image }
if let image = UIImage(key, in: Bundle(for: BrandManager.self)) { return image }
print("Failed to find \(key.rawValue) in any bundle")
return nil
}
convenience init?(_ key: Key, in bundle: Bundle? = nil) {
self.init(named: key.rawValue, in: bundle, compatibleWith: nil)
}
}
This is fine, but obviously it means I need to add .with every time i.e. UIImage.with(.key) when I'd prefer to use the convenience init directly to drop with
Looking here Swift unwrap optional init inside convenience init
this isn't possible with convenience init... but is there another a way to get the syntax and look in multiple bundles? I can bury it inside UIImageView but I'm looking for it directly on UIImage
Thanks
As per the answer by #JeremyP
I tried url(forResource... but for some reason it always came back as nil... It was a good idea though...
Here's what I have, it feels pretty ugly to build the image twice.. but as I said the other one always came back with nil for the url. I tried adding the extension but it didn't help.
convenience init?(_ key: Key, in bundle: Bundle? = nil) {
var correctBundle: Bundle?
let bundles = [bundle,
.main,
Bundle(for: BrandManager.self)].compactMap { $0 }
for b in bundles {
guard UIImage(named: key.rawValue, in: b, compatibleWith: nil) != nil else { continue }
// guard b.url(forResource: key.rawValue, withExtension: nil) != nil else { continue }
correctBundle = b
break
}
self.init(named: name, in: correctBundle, compatibleWith: nil)
}
If you would accept UIImage[.key] as a plausible calling syntax, you could express your factory method as a static subscript.
Having said in the comments that I see nothing wrong with the with function, you can dispense with it.
Instead of trying to initialise the image directly, you can first search for it in all the bundles by looking for the path name or URL using e.g. Bundle.url(forResource:withExtension:) and then load the image from the first bundle where that returns non nil (or even use the URL to initialise the image).

CGImage/ImageIO Code works in playground but not in OSX app

This routine returns nil in OSX 10.13.2 Beta but not in a playground. Don't have an older OS to test with at the moment.
func getImage(_ url: CFURL) -> CGImage? {
let sourceOptions = [
kCGImageSourceShouldAllowFloat as String: kCFBooleanTrue as NSNumber
] as CFDictionary
guard let imageSource = CGImageSourceCreateWithURL(url, sourceOptions) else { return nil }
guard let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) else {
let imageSourceStatus = CGImageSourceGetStatus(imageSource)
Swift.print("image nil, Image Source Status = \(imageSourceStatus)")
return nil
}
return image
}
imageSource is non-nil, but image is nil. The console message is "Image Source Status = CGImageSourceStatus", which is not one of the valid enum values.
Tried with both Swift 3.2 and Swift 4.0. The Dictionary arg in CGImageSourceCreateWithURL can be set to nil; nothing changes.
The correct frameworks are in the project (although it linked without them, so I'm not sure they matter.) Did "import ImageIO" but it built without it, so again I'm not sure in matters.
The URL is absolutely a valid file URL -- like I said, this works in the playground, and I've tried a number of different files and file types (tiff, jpg and png).
Any ideas?

Delete picture from UIImageView

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")
}

fatal error: unexpectedly found nil while unwrapping an Optional value CMMotionManager

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.

My Code quit working after a week - fatal error: unexpectedly found nil while unwrapping an Optional value

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.