i am trying to use UIImagepickerController to pick an image from photos.
I am using the function below in my gameScene class
(this is for importing images into a game)
But I get the error "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
on this line
self.view!.window!.rootViewController!
the function is below. I am not sure how to fix it and have searched for an answer without much luck, so any help would be great.
func getPhotoFromSource(source:UIImagePickerControllerSourceType ){
if UIImagePickerController.isSourceTypeAvailable(source)
{
let imagePicker = UIImagePickerController()
imagePicker.modalPresentationStyle = .currentContext
imagePicker.delegate = self
imagePicker.sourceType = source
imagePicker.allowsEditing = false
if (source == .camera){
imagePicker.cameraDevice = .front
}
let vc:UIViewController = self.view!.window!.rootViewController! //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
vc.present(imagePicker, animated: true, completion: nil)
} }
instead of
let vc:UIViewController = self.view!.window!.rootViewController!
, use optional chaining and try
guard let vc = self.view?.window?.rootViewController else {
print("something went wrong")
}
Seeing how it's either your view or your window or your rootViewController that's not there when you try to force unwrap, if you run the code above your code will just run the print statement above.
Can you share your code for setting up your viewController?
Related
I'm building a video editor that lets you apply a CIFilter to a video. And it works well.
The only problem I'm facing is that when I dismiss the ViewController I get this error:
Unfinished AVAsynchronousVideoCompositionRequest deallocated - should
have called finishWithComposedVideoFrame:, finishWithError: or
finishCancelledRequest
This error doesn't make the app crash or slower, but when I try to edit another video the preview in the AVPlayer becomes black.
This is my current code:
var mutableComposition = AVMutableVideoComposition()
let exposureFilter = CIFilter.exposureAdjust()
override func viewDidLoad() {
updateComposition()
}
func updateComposition() {
mutableComposition = AVMutableVideoComposition(asset: player.currentItem!.asset, applyingCIFiltersWithHandler: { [weak self] request in
guard let self = self else {
return
}
self.exposureFilter.inputImage = request.sourceImage.clampedToExtent()
self.exposureFilter.ev = 5
let output = self.exposureFilter.outputImage!.cropped(to: request.sourceImage.extent)
request.finish(with: output, context: nil)
})
player.currentItem?.videoComposition = mutableComposition
}
If I remove the [weak self] no error it's printed, but it keeps the ViewController in memory when I dismiss it, creating an unwanted memory leak.
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 application that works well on ios8. However after updating everything to ios9 I am having problem with nill values. I cant figure out what value is nil. Here is the code:
func resetToChosenPage(index: Int!) {
/* Getting the page View controller */
pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
self.pageViewController.dataSource = self
pageContentViewController = self.viewControllerAtIndex(index)
if pageContentViewController != nil {
self.pageViewController.setViewControllers([pageContentViewController], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
}
/* We are substracting 30 because we have a start again button whose height is 30*/
self.pageViewController.view.frame = CGRectMake(0, self.navigationController!.navigationBar.frame.height , self.view.frame.width, self.view.frame.height - 30)
self.addChildViewController(pageViewController)
self.view.addSubview(pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
func viewControllerAtIndex(index : Int) -> UIViewController? {
if((dataArray.count == 0) || (index >= dataArray.count)) {
return nil
}
let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SingleArticleViewController") as! SingleArticleViewController
self.delegate = pageContentViewController
pageContentViewController.delegate = self
// pageContentViewController.delegateWebView = self
pageContentViewController.singleArticleIndex = index
pageContentViewController.categoryID = categoryID
pageContentViewController.dateOfPub = dataArray[index].pubDate
pageContentViewController.category = dataArray[index].category
pageContentViewController.newsTitle = dataArray[index].pageTitle
pageContentViewController.videoLink = dataArray[index].videoLink
return pageContentViewController
}
One line self.pageViewController.SetViewControllers([pageContentViewController]... I have error "fatal error: unexpectedly found nil while unwrapping an Optional value". The fact is this code works well on ios8. I checked and could not find nil values. Moreover, I checked all identifiers of storyboard but they are correct. Guys, what can be a problem if this code works on ios8?
I suggest try changing the if clause that wraps the setViewControllers: call so that it explicitly checks for both the pageContentViewController and the pageViewController:
if let pageVC = self.pageViewController, let contentVC = self.pageContentViewController {
pageVC.setViewControllers([contentVC], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
}
As a general thing, I would try to avoid using Implicitly Unwrapped Optionals (like that Int! in your resetToChosenPage: method. As they lead to these 'unexpectedly found nil' errors.
Also, since your resetToChosenPage: method doesn't check if the pageViewController has already been instantiated, calling it multiple times will result in many instances of the PageViewController being instantiated and piled on top of each other. Which is probably not what you want.
Anyone knows the correct way to instantiate a view using NSNib in Swift ?
The code below crashes.
import Cocoa
class ViewController: NSViewController {
var myview:NSView!
override func viewDidLoad() {
super.viewDidLoad()
let obj = AutoreleasingUnsafeMutablePointer<NSArray?>()
if let success = NSNib(nibNamed: "View", bundle: NSBundle.mainBundle())?.instantiateWithOwner(self, topLevelObjects: obj) where success {
if let m = obj.memory { // fatal error:
myview = m[0] as! NSView
}
}
}
}
You are seeing the fatal error there because the value you are trying to access is nil and you are forcefully trying to unwrap the optional. You should safely unwrap optionals this is what they are meant for. So, always use if statement when you try to access optionals, then you won't get this error.
I have a default image in viewItem to make sure that it is working, it shows on the detail view of the splitview.
#IBOutlet weak var ImageView: UIImageView!
var imageCache = [String: UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
self.configureView()
}
func configureView() {
if let detail: AnyObject = self.detailItem {
if let label = self.detailDescriptionLabel {
let dict = detail as [String: String]
label.text = ""
let s = dict["result"]
let vr = NString(string: s!)
let vrd = vr.doubleValue
let value = ceil(vrd*20)
let valueString = String(format: "%.0f", value)
vresult.text = "\(valueString)%"
getPic(dict) // <---- trouble maker
fitem.hidden = false
ritem.hidden = false
}
} else {
navigationController?.popViewControllerAnimated(true)
}
}
func getPic(item: [String: String]) {
var chachedImage = self.imageCache[item["image"]!]
println(item["image"]) // <-- prints out the url
if cachedImage == nil {
var imgUrl = NSURL(string: item["image"]!)
let request: NSURLRequest = NSURLRequest(URL: imgUrl!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {( reponse: NSURLResponse!, data: NSData!, error; NSError!) -> Void in
if error == nil {
cachedImage = UIImage(data: data)
println("got here no problem") // <-- prints out
self.imageCache[item["image"]!] = cachedImage
println(self.imageCache) // <-- prints reference OK
dispatch_async(dispatch_get_main_queue(), {
self.ImageView.image = cachedImage // <---- offender
})
} else {
println("Error: \(error.localizedDescription)")
}
})
} else {
dispatch_async(dispatch_get_main_queue(), {
self.ImageView.image = cachedImage
})
}
}
ImageView is coming up nil every time.
fatal error: unexpectedly found nil while unwrapping an Optional value
but the default image shows. I've moved this out of the dispatch and even tried setting it straight from the viewDidLoad() always errors. It used to be a UIWebView and worked perfectly except that it would not cache anything. Since loading these images is a lot of work, I thought caching would be good, I've got caching working for thumbnails in the MASTER view.
It may be because of how your instaciating your viewcontroller.
let vc = MyViewController()
Something like this wont work. You're creating the VC without actually giving the storyboard a chance to link the IBOutlets. Instead use
storyboard.instantiateViewControllerWithIdentifier(identifier: String)
You may need to get reference to the storyboard using
let storyboard = UIStoryboard(name: name, bundle: NSBundle.mainBundle())
Hope this helps :)
Changing your variable name shouldn't make any difference except for readibility/maintainability unless there's a namespace conflict (good to understand why/where that might be happening). Also I was wondering - you made the IBOutlet'ed varable weak. When the last remaining strong ref to the object goes away, the weak references to the object are set nil by the runtime/garbage collector automatically. (Look up that section of the Swift documentation if you're not solid about it).
Maybe you should check your classes and controllers by adding deinit { println(,"function name deallocated' }. Between your use of weak and improved behavior seen when you change the variable name, it seems like there might be some weird (buggy) interactions going on in your app itself.
Well silly me. I've been working on this for a few days, I got the great idea to try and change the name, and it worked. I tried changing it back and it broke, apparently you can't use ImageView as a variable!
In my case was because I was using a nib and didn't register it.
Once I did registered it, it worked
My case Was Different I used
awakeFromNib()
instead of
viewDidLoad()
.