ios - 在 AppDelegate Swift 中传递全局用户名

标签 ios swift authentication appdelegate

继我发布的另一个问题之后,我现在尝试在 AppDelegate 类中快速声明一个全局用户名变量。我的目标是让用户在启动屏幕中输入他的用户名,然后让该用户名在其他 View 的标签上弹出 - 一个简单的通用用户名。

我已经在我的 AppDelegate 类中声明了用户名

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var userName = ""

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

在我的主 Controller 中,我有一个标签和一个设置名称的按钮功能

class ViewController: UIViewController {

    @IBOutlet var userLabel : UILabel!

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func setName (){ 
        appDelegate.userName = userLabel.text!;

    }
}

当时的想法是,这个名称将在我的 player2 Controller 的标签中弹出

import Foundation
import UIKit

class Player2 : UIViewController {

    @IBOutlet var player2 : UILabel!

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.player2.text = appDelegate.userName as? String

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

最佳答案

这是将 userName 从一个 ViewController 传递到另一个 ViewController 的简单方法。

//Set your userName with specific key 
@IBAction func setName (){
    NSUserDefaults.standardUserDefaults().setObject(userLabel.text, forKey: "userName")
}

之后,您可以通过这种方式从 SecondViewController 读取该值:

override func viewDidLoad() {
    super.viewDidLoad()
    let userName = NSUserDefaults.standardUserDefaults().objectForKey("userName") as! String
    player2.text = "\(userName)"

}

您不需要在 AppDelegate 类中声明任何变量。

只需从 ViewController 类中的 userLabel.text 获取值并存储它。之后,您可以在项目的任何位置从 NSUserDefaults 读取它。

关于ios - 在 AppDelegate Swift 中传递全局用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31827221/

相关文章:

ios - 我如何将视频从 swift 存储到 firebase 存储中?

ios - Facebook SDK FBSession 代码不适用于 Swift

ios - 如何以编程方式更改或更新 NSLayoutConstraint

swift - 无法将类型 'Observable<String>' 的值转换为预期参数类型 'BehaviorRelay<String>'

android - Xamarin 表单 : How to open an app from another app?

ios - 动态证书固定

ios - 在 Swift 中将日期转换为 "/Date(631148400000+0100)/"字符串

javascript - PHP登录脚本重定向在登录后不起作用

scala - Play2.2.x、BodyParser、身份验证和 Future[结果]

android - 登录Activity和Main Activity的简单Android设计流程查询