如何解决使用URL打开应用程序时,将数据从Scene Delegate传递到ViewController
在Firebase电子邮件验证期间通过URL动态链接启动应用程序时,我需要在初始控制器上显示视图并设置UILabel。
我遇到的问题是标签未初始化,因此应用程序在此过程中崩溃。我尝试了很多方法,但是即使打开了应用程序,打开动态链接时也无法显示我的视图并设置标签。
场景委托
func scene(_ scene: UIScene,continue userActivity: NSUserActivity) {
if let link = userActivity.webpageURL?.absoluteString
{
if Auth.auth().isSignIn(withEmailLink: link) {
Config().verifyEmail(link: link)
}
}
}
AppDelegate
@main
class AppDelegate: UIResponder,UIApplicationDelegate {
var errorText: String?
var errorType: Bool?
func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
return true
}
ViewController
func loadErrorInfo()
{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if let eText = appDelegate.errorText,let eType = appDelegate.errorType {
errorCall(message: eText,error: eType)
} else {
errorBox.isHidden = true
}
}
func errorCall(message: String,error: Bool)
{
if error {
self.errorLabel.textColor = UIColor.yellow
self.errorLabel.text = message
self.errorBox.isHidden = false
self.errorBox.shake()
} else {
self.errorLabel.textColor = UIColor.white
self.errorLabel.text = message
self.errorBox.isHidden = false
self.errorBox.shakeL()
}
}
自定义配置NSObject类
import UIKit
import FirebaseAuth
open class Config: NSObject {
public func verifyEmail(link: String)
{
var email = ""; var password = ""
if let x = UserDefaults.standard.object(forKey: "Email") as? String { email = x }
if let y = UserDefaults.standard.object(forKey: "Password-\(email)") as? String { password = y }
if password != "" && email != ""
{
Auth.auth().signIn(withEmail: email,link: link) { (user,error) in
if let use = user,error == nil
{
Auth.auth().currentUser?.updatePassword(to: password) { (error) in
if let error = error
{
print(error)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.errorText = error.localizedDescription
appDelegate.errorType = true
ViewController().loadErrorInfo()
}
else
{
print(use,"Logged In")
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.errorText = "\(use) Logged In"
appDelegate.errorType = false
ViewController().loadErrorInfo()
}
}
}
}
}
}
}
不确定其他方法是否可以使用。总而言之,在单击电子邮件中的动态链接后,我想在作为初始控制器的主ViewController上更改UILabel。目前,每种方法都会导致其崩溃,因为尚未设置UILabel,即使控制器已经初始化。
解决方法
通过再次初始化控制器并更新根控制器来对其进行修复。
// SceneDelegate
func changeRootViewController(_ vc: UIViewController,animated: Bool = true)
{
guard let window = self.window else {
return
}
window.rootViewController = vc
}
//重新初始化
let storyboard = UIStoryboard(name: "Main",bundle: nil)
let destinationNavigationController = storyboard.instantiateViewController(withIdentifier: "ViewController2")
(UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.changeRootViewController(destinationNavigationController)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。