John Doe
John Doe

Reputation: 876

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'

Upvotes: 5

Views: 5418

Answers (3)

kaushal
kaushal

Reputation: 1573

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 { }

Upvotes: 2

Acey
Acey

Reputation: 8098

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

Upvotes: 11

f0go
f0go

Reputation: 272

You can use:

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

which is compatible with iOS 7 and iOS 8

Upvotes: 3

Related Questions