Swift:在 AppDelegate.swift 中执行 Segue

标签 swift

我已经在我的 AppDelegate.swift 文件中成功地将 Google Sign-In 集成到我的 iOS 应用程序中,并且可以成功检测到成功的登录(通过在控制台上打印“成功”)。问题是,在成功登录后,当我想进入应用程序的下一个屏幕时,我又回到了 Google 登录页面。

AppDelegate.swift 文件无法识别 performSegue 函数,因为它是 UIViewController 类的函数(如果我错了请纠正我)。为了解决这个问题,我在 ViewController 文件中创建了一个全局变量,这样只要该值发生更改,就会执行 segue:

AppDelegate.swift:

var userSignedInGlobal = "n/a"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {

    // A bunch of code that implements the Google Sign in ...

    print("Successfully logged into Google.", user)
    userSignedInGlobal = "success"

}

然后是我的 InitialViewController.swift 文件:

class InitialViewController: UIViewController, GIDSignInUIDelegate  {

    var userSignedIn = userSignedInGlobal {
        didSet {
            performSegue(withIdentifier: "segueOne", sender: self)
        }
    }

    // A bunch of irrelevant code.

}

这不起作用,我认为这不起作用的原因是 InitialViewController.swift 文件中的 userSignedInGlobal 是通过引用传递的——所以即使它的值发生变化,userSignedIn 的值也不会改变(同样,如果我错了,请纠正我)。

为了解决这个问题,我按如下方式更改了 InitialViewController.swift 文件:

var userSignedIn = userSignedInGlobal {
    didSet {
        doSegue()
    }
}

class InitialViewController: UIViewController, GIDSignInUIDelegate  {

    func doSegue() {
        performSegue(withIdentifier: "segueOne", sender: self)
    }

    // A bunch of irrelevant code.

}

这在第三行给了我一个错误:“使用未解析的标识符‘doSegue()’”

登录成功后,我不知道如何进行转场。任何帮助将不胜感激,在此先感谢。

最佳答案

这里有几个问题:

  1. App Delegate 中的全局变量

有许多答案展示了如何在您的 AppDelegate 中存储一个全局变量,然后在您的 View Controller 中引用该变量,例如getting a reference to app delegate

  1. 仅从基于 Storyboard 的 Controller 执行 Segue

您将无法使用 performSegue,除非您当前的 View Controller 是从 StoryBoard 加载的(参见 performSegue)。这可能不是您从 AppDelegate 加载的任何 Google View 的情况。

  1. 您是否在正确的地方登录?

您可能需要重新考虑 AppDelegate 和初始 View Controller 之间的职责划分。或许您试图在 AppDelegate 中做太多事情。也许您应该将部分代码(显示 Google 表单)移动到您的初始 VC,然后根据结果继续或重置您的导航 Controller 。

希望这对您有所帮助。

关于Swift:在 AppDelegate.swift 中执行 Segue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46761076/

相关文章:

ios - 如果秒 == 60,为什么我的分钟不会改变

ios - LazyVGrid 中的 SwiftUI NavigationLink 选择随机索引

ios - iPhone 设备中的 Json 解析错误,但在模拟器中正确

swift - 嵌套完成处理程序不返回要发送到 TableViewController 的项目

ios - 在 Swift 的 UIImageView 中加载图像时出现内存警告

Swift 4 : Inbuilt String. hashValue 为不同的字符串生成相同的结果

ios - 在静态表格 View 中重用表格单元格 - iOS - Swift

ios - 代码错误 : "Use of unresolved identifier: GGLContext" (without CocoaPods)

ios - AWS S3 iOS - 了解列出对象何时完成

swift -/usr/bin/ld : cannot find -lstdc++ for Ubuntu while trying to "swift build" Perfect2 project