错误:“AppDelegate?”类型的值没有成员“在场”

Posted

技术标签:

【中文标题】错误:“AppDelegate?”类型的值没有成员“在场”【英文标题】:Error: Value of type 'AppDelegate?' has no member 'present' 【发布时间】:2017-08-12 07:46:55 【问题描述】:

我收到一个错误

'AppDelegate?' 类型的值没有成员“在场”

当我试图让我的用户保持登录状态时,即使应用程序已退出。

这是我的视图控制器,知道如何让我的用户保持登录状态吗?为什么会出现这个错误?

我在我的代码中使用 Firebase 作为我的数据库。

LoginViewController.swift

import UIKit
import Firebase

class LoginViewController: UIViewController, UITextFieldDelegate 

    @IBOutlet weak var emailField: UITextField!
    @IBOutlet weak var pwField: UITextField!




    func createAlert(title:String, message:String) 

        let alert=UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)


        alert.addAction(UIAlertAction(title: "error" , style: UIAlertActionStyle.default, handler:  (action) in alert.dismiss(animated: true, completion: nil)
        ))

        self.present(alert, animated:true, completion: nil)
    





  /*  @IBAction func emailKeyboardField(_ sender: Any) 

       hideKeyboard()
    

    func hideKeyboard() 
        emailField.resignFirstResponder()
        pwField.resignFirstResponder()

    
    */

    override func viewDidLoad() 
        super.viewDidLoad()

        emailField.delegate = self


        // Do any additional setup after loading the view.
    



    func emailKeyField(_ emailField: UITextField) -> Bool 
        self.view.endEditing(true)


        return true
    


    @IBAction func loginPressed(_ sender: Any) 

        guard emailField.text != "", pwField.text != "" else return

        FIRAuth.auth()?.signIn(withEmail: emailField.text!, password: pwField.text!, completion:  (user, error) in

            if let error = error 
                print(error.localizedDescription)

                self.createAlert(title: "Error", message: "We could not locate your account. Check your email and password.")
            


            if let user = user 
                let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "usersVC")

                self.present(vc, animated: true, completion: nil)
            
        )


    



AppDelegate.swift

import UIKit
import Firebase


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate 

    var window: UIWindow?
    var actIdc = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
    var container: UIView!
    private let auth = FIRAuth.auth()

    class func instance() -> AppDelegate 
        return UIApplication.shared.delegate as! AppDelegate
    


    func showActivityIndicator() 
        if let window = window 
            container = UIView()
            container.frame = window.frame
            container.center = window.center
            container.backgroundColor = UIColor(white: 0, alpha: 0.8)

            actIdc.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
            actIdc.hidesWhenStopped = true
            actIdc.center = CGPoint(x: container.frame.size.width / 2, y: container.frame.size.height / 2)

            container.addSubview(actIdc)
            window.addSubview(container)

            actIdc.startAnimating()
        
    

    func dismissActivityIndicatos() 
        if let _ = window 
            container.removeFromSuperview()
        
    

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 



                auth?.addStateDidChangeListener  [weak self] (_, user) in

                    if let user = user 
                        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "usersVC")

                        self.present(vc, animated: true, completion: nil) //error on this line
                        // user is already logged in
                     else 
                        // user is not logged in
                    


        
        FIRApp.configure()
        return true
    


    func applicationWillResignActive(_ application: UIApplication) 
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    

    func applicationDidEnterBackground(_ application: UIApplication) 
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    

    func applicationWillEnterForeground(_ application: UIApplication) 
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    

    func applicationDidBecomeActive(_ application: UIApplication) 
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    

    func applicationWillTerminate(_ application: UIApplication) 
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    



我们将不胜感激。

【问题讨论】:

【参考方案1】:

App 委托不是 ViewController 类型,因此它没有显示视图的 present 方法。相反,您可以做的是使用它的窗口显示一个视图,例如:

let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let homeC = storyboard.instantiateViewController(withIdentifier: "YOUR_VIEWCONTROLLER_IDENTIFIER_IN_STORYBOARD") as? HomeC
    if homeC != nil 
        homeC!.view.frame = (self.window!.frame)
        self.window!.addSubview(homeC!.view)
        self.window!.bringSubview(toFront: homeC!.view)
    

【讨论】:

这会让我的用户保持登录状态吗? 把它放在你使用 self.present(vc, animated: true, completion: nil) 的地方,你的登录逻辑应该保持原样,但由你来处理。

以上是关于错误:“AppDelegate?”类型的值没有成员“在场”的主要内容,如果未能解决你的问题,请参考以下文章

AppDelegate 类型的值没有成员 managedObjectContext

Swift:实现快捷方式项目(3D 触摸)共享项目错误“AppDelegate 类型的值没有当前成员”

“AppDelegate”类型的值没有成员“manageObjectContext”

AppDelegate 类型 var 不是成员,除非在 func 中(见图)

静态成员“负载”不能用于“AppDelegate”类型的实例

“AppDelegate”类型的IOS开发值没有成员“managedObjectContext”Xcode 10