使用swift 3运行xcode 8
以下是我的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
好像我无法从AppDelegate.swift获取设备令牌字符串。 我怎么能得到它?
或者我可以在didFinishLaunchingWithOptions中获取设备令牌吗?
答案 0 :(得分:3)
viewDidLoad
在viewController的 AppDelegate
后始终执行,这就是字符串为空的原因。
解决您可以做的时间问题
在weak var viewController : ViewController?
声明弱属性。
ViewController
在viewDidLoad
> guard
设置属性。您不需要AppDelegate
override func viewDidLoad() {
print("inside viewDidLoad ")
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.viewController = self
}
。如果它不在那里,应用程序将无法启动。
ViewController
在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)
}
中,加载Web请求的代码是一种额外的方法。
AppDelegate
在didRegisterForRemoteNotificationsWithDeviceToken
> viewController?.loadRequest(for: deviceTokenString!)
调用该方法。
{{1}}