swift 如何从外部框架呈现视图控制器?

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

我制作了一个框架,其中包含一个名为 "AuthenticationViewController.h" 的视图控制器和 nib "AuthenticationViewController.xib"。一个用于测试的示例项目用于呈现 AuthenticationViewController。 在 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];

这对我来说很好。

但是当我在 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)

应用程序因错误而崩溃:-

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

NSBundle(identifier: "SendOTPFramework"),不是NSBundle(path: <#T##String#>)?你确定有可用的标识符吗?你在不同的语言中使用了不同的函数。

解决方案 swift 5 并使用 class 的名称而不是框架标识符:

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

也不需要将Xib的根视图作为出口连接到文件所有者。

Xcode13、Swift5.5和iOS15.

您在 Framework SDKStoryboard 中的故事板和您在该故事板中的 vc 名称 HelloLogger

//Working fine
let s = UIStoryboard(name: "SDKStoryboard", bundle: Bundle(for: HelloLogger.self))
let vc = s.instantiateInitialViewController()!
//self.present(vc, animated: true, completion: nil) //To present VC
self.navigationController?.pushViewController(vc, animated: true) //Push VC

如果你想要另一种风格How to show View Controller from Framework(SDK) in Swift?