Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to present a view controller from an external framework in swift?

I have made a framework with a view controller named "AuthenticationViewController.h" with nib "AuthenticationViewController.xib". And a sample project to test have used to present AuthenticationViewController. In Objective-C:

NSString *frameworkDirPath = [[NSBundle mainBundle] privateFrameworksPath];
NSString *frameworkBundlePath = [frameworkDirPath stringByAppendingPathComponent:@"xxx.framework"];
NSBundle *frameworkBundle = [NSBundle bundleWithPath:frameworkBundlePath];
AuthenticationViewController *authenticationViewController = [[AuthenticationViewController alloc]initWithNibName:@"AuthenticationViewController" bundle:frameworkBundle];
authenticationViewController.delegate = self;
[self presentViewController:authenticationViewController animated:YES completion:nil];

Which works fine for me.

But when I use following code in Swift:

let frameworkBundle = NSBundle(identifier: "xxx")

let authViewControler :AuthenticationViewController = AuthenticationViewController.init(nibName: "AuthenticationViewController", bundle: frameworkBundle)
authViewControler.delegate = self
self.presentViewController(authViewControler, animated: true, completion: nil)

The app crashes with error:-

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle (loaded)' with name 'AuthenticationViewController''

like image 263
Hussain Chhatriwala Avatar asked Jan 06 '16 06:01

Hussain Chhatriwala


People also ask

How do I present a view controller from another view controller?

Using segues in your storyboard is the recommended way to present and dismiss view controllers. A segue is a visual representation of a transition from one view controller to another. A segue starts with an action such as a button tap or table-row selection in the initial view controller.


2 Answers

NSBundle(identifier: "SendOTPFramework"),Not NSBundle(path: <#T##String#>)?Are you sure there is an available identifier?You used different function in different lang.

like image 57
Lumialxk Avatar answered Nov 02 '22 11:11

Lumialxk


Solution for swift 5 and using the name of the class instead of the framework identifier:

let bundle = Bundle(for: AuthenticationViewController.self)
    let VC = AuthenticationViewController(nibName: "AuthenticationView", bundle: bundle)
    self.present(VC, animated: true, completion: nil)

It is also needed no connect the root view of the Xib to the file owner as outlet.

like image 33
Hugo Jordao Avatar answered Nov 02 '22 10:11

Hugo Jordao