Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

showViewController Not Working

I am developing an app in SWIFT and I am using the following code to show a view controller on a button click.

let storyboard = UIStoryboard(name: "Main", bundle: nil);
var viewName:NSString = "websiteView"
let vc = storyboard.instantiateViewControllerWithIdentifier(viewName) as WebsiteViewController
self.showViewController(vc, sender: self)

it works perfectly when I test it for ios 8 but on ios 7 no matter what I do I get the following error message. I read on a forum that self.showViewController was only available for ios 8 but the compiler doesn't throw an error, does anyone know if I can use it?

showViewController:sender:]: unrecognized selector sent to instance 0x7f9552e7cc50

2014-11-15 09:25:49.565 Throw[80595:613] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Throw.test showViewController:sender:]: unrecognized selector sent to instance 0x7f9552e7cc50'

like image 914
John Doe Avatar asked Nov 15 '14 09:11

John Doe


3 Answers

The compiler didn't throw an error because you have the iOS 8.0 (or 8.1) SDK selected. That method is indeed iOS 8.0+ only. You can choose to use it if you call it conditionally, like so:

if (self.respondsToSelector(Selector("showViewController"))) {
    self.showViewController(vc, sender: self)
} else {
    //An example of the alternate if you are using navigation controller
    self.navigationController?.pushViewController(vc, animated: true)
}
like image 99
Acey Avatar answered Oct 15 '22 18:10

Acey


You can use:

self.navigationController?.pushViewController(vc as WebsiteViewController, animated: true)

which is compatible with iOS 7 and iOS 8

like image 3
f0go Avatar answered Oct 15 '22 20:10

f0go


Update - A better and recommended way from swift2 for API version compatibility check

if #available(iOS 8, *) {
   self.showViewController(vc, sender: self)
} else {
  self.navigationController?.pushViewController(vc, animated: true)
}

Bonus : Use the @available attribute to decorate individual functions or entire classes this will give compile time version check for your own API

@available(iOS 8, *)
func compatibalityCheckForiOS8() -> Void { }
like image 2
kaushal Avatar answered Oct 15 '22 18:10

kaushal