Reputation: 8506
Running on Xcode 8 with swift 3
Below is my 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()
}
}
Below is my AppDelegate.swift file
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)
}
}
Now, I can get device id in ViewController and also get device token in AppDelegate file.
However, how can I pass device token to my testURL in ViewController or how can I pass both device id and device token to testURL?
Upvotes: 1
Views: 1592
Reputation: 7595
Make deviceTokenString
a property in AppDelegate
class.
class AppDelegate: UIResponder, UIApplicationDelegate {
...
var deviceTokenString: String?
...
...
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// feed your property
deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("===== deviceTokenString =====")
print(deviceTokenString)
}
}
Now, from any of the controller you can get your deviceTokenString
like:
override func viewDidLoad() {
super.viewDidLoad()
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
guard let deviceTokenString = appDelegate.deviceTokenString else {
// deviceTokenString isn't available
return
}
// deviceTokenString is available here
let deviceid = UIDevice.current.identifierForVendor!.uuidString
// I want to pass device id and device token to this testURL
// Concat various types into string like below
let testURL = URL(string: "http://www.test.com/user.html?device=ios&deviceid=\(deviceid)&devicetoken=\(deviceTokenString)")
let testURLRequest = URLRequest(url: testURL!)
TestWebview(testURLRequest)
}
Upvotes: 1