與SWIFT 3如何在webview加載之前獲取設備標識和設備標記?
下面運行在Xcode中8是我ViewController.swift
class ViewController: UIViewController {
@IBOutlet weak var TestWebview: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let deviceid = UIDevice.current.identifierForVendor!.uuidString
//I want to pass device id and device token to this testURL
let testURL = URL(string: "http://www.test.com/user.html?device=ios&deviceid=" + deviceid + "&devicetoken=")
let testURLRequest = URLRequest(url: testURL!)
TestWebview(testURLRequest)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
下面是我的AppDelegate.swift文件
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
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) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("===== deviceTokenString =====")
print(deviceTokenString)
}
}
現在,我可以在視圖控制器獲取設備ID和也可以在AppDelegate文件中獲取設備令牌。
但是,如何將設備令牌傳遞給ViewController中的testURL,或者如何將設備標識和設備令牌傳遞給testURL?
將名爲'deviceTokenString'財產。然後在你使用'reduce'方法的地方加入這個屬性。然後從任何視圖控制器,獲取'AppDelegate'實例並訪問'deviceTokenString'。 (即:'guard let appDelegate = UIApplication.shared.delegate as?AppDelegate else { return } let deviceTokenString = appDelegate.deviceTokenString') – nayem