運行的Xcode 8與SWIFT 3如何將設備令牌從AppDelegate.swift傳遞到ViewController.swift?
下面是我的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)
}
}
下面是我的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!)
}
}
下面是我的調試區域信息
YES。
inside viewDidLoad
can not get device token string
==== didRegisterForRemoteNotificationsWithDeviceToken ====
===== deviceTokenString =====
DF9AB59resrF68532C07ECB00627E4632F08F02975D5C4adsfsd2e810A5EB4
它好像我無法從AppD獲取設備標記字符串elegate.swift。 我怎樣才能得到它?
或者我可以在didFinishLaunchingWithOptions中獲得設備令牌嗎?
爲什麼不你剛剛保存設備令牌串到你的userdefaults? –
競態條件問題,我想 – iDhaval
你試圖獲得設備令牌之前,它分配給應用程序委託中的deviceTokenString。 – iDhaval