我想从 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/