swift - 如何使用 Swift 从 ViewController 读取 AppDelegate 中的变量值

标签 swift var

我想从 ViewController 中读取包含在 AppDelegate 中的变量值。该变量包含用于启用 iOS 推送通知的 Device Token,我想在 UILabel 中显示它。

到目前为止,这是我的代码:

AppDelegate.swift

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    internal var deviceTokenToPass: String?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let pushNotificationsTypes: UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
        let pushNotificationsSettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: pushNotificationsTypes, categories: nil)

        application.registerUserNotificationSettings(pushNotificationsSettings)
        application.registerForRemoteNotifications()

        return true
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        let chararacterSet: NSCharacterSet = NSCharacterSet(charactersInString: "<>")
        self.deviceTokenToPass = (deviceToken.description as NSString).stringByTrimmingCharactersInSet(chararacterSet).stringByReplacingOccurrencesOfString(" ", withString: "", options: nil, range: nil) as String
    }
}

ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet var deviceTokenLabel : UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        var deviceToken = appDelegate.deviceTokenToPass

        println(deviceToken) /* nil */

        if deviceToken != nil {
            self.deviceTokenLabel.text = deviceToken
        } else {
            self.deviceTokenLabel.numberOfLines = 4
            self.deviceTokenLabel.text = "Cannot read your device token.\nYou must be using an iOS Simulator or you didn't allowed the application for push notifications"
        }
    }
}

问题是,如果我将 println(deviceToken) 代码放在 AppDelegate.swift 中,设备 token 会正确显示在控制台中,如果我将它放在ViewController.swift 的值将为 nil

最佳答案

如果您确保您想要访问的属性实际上是可读的,那么您可以使用以下内容:

 let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
 let anAttribute = appDelegate.theAttribute

关于swift - 如何使用 Swift 从 ViewController 读取 AppDelegate 中的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28479821/

相关文章:

ios - 确定用户是否允许 iOS 7 中的本地通知

xcode - 当在 Swift Spritekit 中触摸并按住屏幕时,我将如何向上移动我的节点?

c# - 为什么我应该使用 var 而不是类型?

json - POST 请求后在 swift 模型中访问值的问题

ios - 自动布局完成后获取 Collection View 的高度是错误的

ios - 如何快速获取电池信息?

c# - 如何使用 linq 从 var-source 获取值

c# - 在 C# 中使用隐式类型的可空变量?

variables - 为什么可以使用 for 循环声明同一个变量两次?

javascript - IF OR 语句 var = true,则写入文档