简体   繁体   English

如何将设备令牌从AppDelegate.swift传递到ViewController.swift?

[英]How can I pass device token from AppDelegate.swift to ViewController.swift?

Running xcode 8 with swift 3 使用Swift 3运行XCode 8

Below is my ViewController file 下面是我的ViewController文件

class ViewController: UIViewController {

    @IBOutlet weak var testWebview: UIWebView!


    override func viewDidLoad() {
        print("inside viewDidLoad ")
        super.viewDidLoad()

        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
            return
        }
        guard let deviceTokenString = appDelegate.deviceTokenString else {
            print("can not get device token string")
            return
        }


        let deviceid = UIDevice.current.identifierForVendor!.uuidString
        print("====== device id =======")
        print(deviceid)

        let testURL = URL(string: "http://www.test.com/user?device=ios&deviceid=" + deviceid + "&devicetoken=" + deviceTokenString)


        let testURLRequest = URLRequest(url: testURL!)
        print("before load request")
        print(testURL!)
        RJWebview.loadRequest(testURLRequest)
    }

}

Below is my AppDelegate file 以下是我的AppDelegate文件

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var deviceTokenString: String?



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

        let center = UNUserNotificationCenter.current()

        center.requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { granted, error in
            if granted {
                print("YES。")
            }
            else {
                print("NO!")
            }
        })

        application.registerForRemoteNotifications()

        return true
    }


    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
        print("==== didRegisterForRemoteNotificationsWithDeviceToken ====")
        print("===== deviceTokenString =====")
        print(deviceTokenString!)
    }

}

Below is my debug area message 以下是我的调试区域消息

YES。
inside viewDidLoad 
can not get device token string
==== didRegisterForRemoteNotificationsWithDeviceToken ====
===== deviceTokenString =====
DF9AB59resrF68532C07ECB00627E4632F08F02975D5C4adsfsd2e810A5EB4

It seems like I can not get device token string from AppDelegate.swift. 看来我无法从AppDelegate.swift获取设备令牌字符串。 How can I get that? 我该怎么办?

or can I get device token in didFinishLaunchingWithOptions ? 还是可以在didFinishLaunchingWithOptions中获取设备令牌?

didRegisterForRemoteNotificationsWithDeviceToken is executed always after viewDidLoad of the viewController, that's the reason why the string is empty. didRegisterForRemoteNotificationsWithDeviceToken总是 viewController的viewDidLoad 之后执行,这就是字符串为空的原因。

To solve the timing issue you could do 要解决计时问题,您可以做

  • In AppDelegate declare a weak property. AppDelegate声明一个弱属性。

     weak var viewController : ViewController? 
  • In ViewController > viewDidLoad set the property. ViewController > viewDidLoad设置属性。 You don't need to guard AppDelegate . 您无需guard AppDelegate If it was not there the app wouldn't have launched. 如果不存在,该应用程序将无法启动。

     override func viewDidLoad() { print("inside viewDidLoad ") super.viewDidLoad() let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.viewController = self } 
  • In ViewController put the code to load the web request is an extra method. ViewController将代码加载到Web请求中是一种额外的方法。

     func loadRequest(for deviceTokenString : String) { let deviceid = UIDevice.current.identifierForVendor!.uuidString print("====== device id =======") print(deviceid) let testURL = URL(string: "http://www.test.com/user?device=ios&deviceid=" + deviceid + "&devicetoken=" + deviceTokenString let testURLRequest = URLRequest(url: testURL!) print("before load request") print(testURL!) RJWebview.loadRequest(testURLRequest) } 
  • In AppDelegate > didRegisterForRemoteNotificationsWithDeviceToken call the method. AppDelegate > didRegisterForRemoteNotificationsWithDeviceToken调用该方法。

     viewController?.loadRequest(for: deviceTokenString!) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM