Reputation: 19
So, when I try to use the present() function in Swift, it always crashes. Here's my code
func infoOpener(sender: UISwipeGestureRecognizer) {
let location: CGPoint = sender.location(in: tableView)
let cellPath: IndexPath = tableView.indexPathForRow(at: location)!
let VC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "userInfo") as! userInfoVC
VC.username = "@\(self.user[cellPath.row].username)"
VC.imageUrl = self.user[cellPath.row].imagePath
self.present(VC, animated: false, completion: nil)
}
Whenever I use the present(_:animated:completion:)
function, I get an EXC_BREAKPOINT error. Can somebody help me out?
Upvotes: 1
Views: 2403
Reputation: 205
You say your error is: "fatal error: unexpectedly found nil while unwrapping an Optional value" The problem is probably not with present() method but some IBOutlet or variable on your ViewController. Check all your outlets are connected properly or that what you are setting on "username" and "imageURL" is not nil if this variables do not accept nil.
Upvotes: 0
Reputation: 19239
Use if let
or guard let
instead of force unwrapping Optionals with !
to make your code more robust:
func infoOpener(sender: UISwipeGestureRecognizer) {
let location: CGPoint = sender.location(in: tableView)
guard let cellPath: IndexPath = tableView.indexPathForRow(at: location) else {
print("No index path found")
return
}
guard let VC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "userInfo") as? userInfoVC else {
print("View controller could not be instantiated")
return
}
VC.username = "@\(self.user[cellPath.row].username)"
VC.imageUrl = self.user[cellPath.row].imagePath
self.present(VC, animated: false, completion: nil)
}
Upvotes: 3
Reputation: 448
func infoOpener(sender: UISwipeGestureRecognizer) {
let location: CGPoint = sender.location(in: tableView)
let cellPath: IndexPath = tableView.indexPathForRow(at: location)!
if sender.state == .ended /*present in touch end*/ {
let VC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "userInfo") as! userInfoVC
VC.username = "@\(self.user[cellPath.row].username)"
VC.imageUrl = self.user[cellPath.row].imagePath
self.present(VC, animated: false, completion: nil)
}
}
Upvotes: 0