iOS 当应用程序通过推送通知从终止状态打开时,Web View 应用程序崩溃
iOS Web View App crashed when Application is open from kill state through Push Notification
我的应用程序在通过推送通知从终止状态打开时崩溃。如果应用程序已经启动,它会很好用,但是当应用程序被终止时,如果收到任何推送通知并且我点击它,它会使应用程序崩溃。我没有发现任何错误,谁能帮我解决这个问题?
如果我在 AppDelegate.swift
中评论 UNUserNotificationCenter
来自 didFinishLaunchingWithOptions
的代码,则应用程序不会崩溃,但不会根据通知加载视图。我在推送通知中发送 url 并检查它是否为空白然后将其加载为视图。
AppDelegate.swift
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
var apiUrl = "http://www.example.com/api/";
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", [=11=]) }.joined()
// Device Registration with API
deviceRegistration(token)
//print("Token: \(token)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
}
// Device Registration with API
func deviceRegistration(_ token: String) {
let parameters = ["UUID": UIDevice.current.identifierForVendor!.uuidString, "Token": token, "DevOption": "Dev", "MID": "0"]
let url = URL(string: apiUrl + "ios-register")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
request.httpBody = httpBody
let session = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
}
}
}
session.resume()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// Check User Tap the notification
if let notification = response.notification.request.content.userInfo as? [String: AnyObject] {
let message = parseRemoteNotification(notification: notification)
guard let url = message?["url"] as? String else {
return;
}
// If url exists then load the url
if !(url.isEmpty) {
loadView(url)
}
}
completionHandler()
}
private func parseRemoteNotification(notification:[String:AnyObject]) -> NSDictionary? {
if let aps = notification["aps"] as? [String:AnyObject] {
let alert = aps["alert"] as? NSDictionary
return alert
}
return nil
}
func loadView(_ url: String) {
let data: [String: String] = ["url": url]
NotificationCenter.default.post(name: NSNotification.Name("loadWebView"), object: nil, userInfo: data)
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if let sb = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView {
sb.backgroundColor = UIColor.init(red: 252/255, green: 153/255, blue: 0/255, alpha: 1)
}
// Local Notification
//if(application.applicationState == .active) {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
//print("Granted: \(granted)")
}
//}
// Push Notifications
UIApplication.shared.registerForRemoteNotifications()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
ViewControllwer.swift
import UIKit
import WebKit
import UserNotifications
class ViewController: UIViewController, WKNavigationDelegate {
@IBOutlet var mWebKit: WKWebView!
@IBOutlet var indicator: UIActivityIndicatorView!
public var defaultUrl = "https://www.example.com";
public var viewUrl = URL(string: "https://www.example.com")!
override func viewDidLoad() {
super.viewDidLoad()
mWebKit.navigationDelegate = self
self.mWebKit.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
self.mWebKit.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
loadWebView(viewUrl)
// On Notification Receive
NotificationCenter.default.addObserver(forName: NSNotification.Name("loadWebView"), object: nil, queue: nil) { (Notification) in
//print("notification is \(Notification)")
let url = URL(string: Notification.userInfo?["url"] as? String ?? self.defaultUrl)
self.loadWebView(url ?? self.viewUrl)
}
// Do any additional setup after loading the view, typically from a nib.
}
func loadWebView(_ url: URL) {
var request = URLRequest(url: url)
request.setValue("com.example.in", forHTTPHeaderField: "X-REQUESTED-WITH")
self.mWebKit.load(request)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning();
// Dispose of any resources that can be recreated
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(WKWebView.url) {
indicator.startAnimating()
loadWebView(self.mWebKit.url!)
}
if keyPath == #keyPath(WKWebView.estimatedProgress) {
if(self.mWebKit.estimatedProgress == 1) {
indicator.stopAnimating()
}
}
}
}
在这里,我不是 post 为您的答案提供实际解决方案,而是 post 提供您至少 debug
代码的方式。所以,如果你能够保持断点并且能够看到日志(通过使用打印方法),那么,你可以很容易地找到幕后的真正原因。
这是调试这种情况的方法。
- 转到
edit scheme
- 现在,从左侧菜单中 select
Run
打开的屏幕。现在,Select Info
选项卡来自顶部菜单。在这里你会看到 Launch
案例的 2 个单选按钮。 Automatically
默认会被 select 编辑。将其更改为 Wait for executable to be launched
。然后关闭此屏幕。
现在,运行 您的应用在您的设备中。它会在设备上安装您的应用程序,但不会启动您的应用程序,因为它通常每次都会这样做。
现在,post你的推送通知,一旦你收到通知,点击它。当你点击它时,你的应用程序将启动,你的调试会话将开始,如果你的应用程序崩溃,断点将自动停止在那里。否则,如果您的逻辑有任何问题,您可以通过放置断点以及添加 "print" 日志来调试会话,在任何需要的地方。
我认为通过执行以上操作,您将能够进行调试,并且一旦可以调试,您就可以轻松识别问题并找到解决方案。获得解决方案后,将上述设置更改回 Automatically
以正常启动您的应用程序。
我的应用程序在通过推送通知从终止状态打开时崩溃。如果应用程序已经启动,它会很好用,但是当应用程序被终止时,如果收到任何推送通知并且我点击它,它会使应用程序崩溃。我没有发现任何错误,谁能帮我解决这个问题?
如果我在 AppDelegate.swift
中评论 UNUserNotificationCenter
来自 didFinishLaunchingWithOptions
的代码,则应用程序不会崩溃,但不会根据通知加载视图。我在推送通知中发送 url 并检查它是否为空白然后将其加载为视图。
AppDelegate.swift
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
var apiUrl = "http://www.example.com/api/";
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", [=11=]) }.joined()
// Device Registration with API
deviceRegistration(token)
//print("Token: \(token)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
}
// Device Registration with API
func deviceRegistration(_ token: String) {
let parameters = ["UUID": UIDevice.current.identifierForVendor!.uuidString, "Token": token, "DevOption": "Dev", "MID": "0"]
let url = URL(string: apiUrl + "ios-register")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
request.httpBody = httpBody
let session = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
}
}
}
session.resume()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// Check User Tap the notification
if let notification = response.notification.request.content.userInfo as? [String: AnyObject] {
let message = parseRemoteNotification(notification: notification)
guard let url = message?["url"] as? String else {
return;
}
// If url exists then load the url
if !(url.isEmpty) {
loadView(url)
}
}
completionHandler()
}
private func parseRemoteNotification(notification:[String:AnyObject]) -> NSDictionary? {
if let aps = notification["aps"] as? [String:AnyObject] {
let alert = aps["alert"] as? NSDictionary
return alert
}
return nil
}
func loadView(_ url: String) {
let data: [String: String] = ["url": url]
NotificationCenter.default.post(name: NSNotification.Name("loadWebView"), object: nil, userInfo: data)
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if let sb = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView {
sb.backgroundColor = UIColor.init(red: 252/255, green: 153/255, blue: 0/255, alpha: 1)
}
// Local Notification
//if(application.applicationState == .active) {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
//print("Granted: \(granted)")
}
//}
// Push Notifications
UIApplication.shared.registerForRemoteNotifications()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
ViewControllwer.swift
import UIKit
import WebKit
import UserNotifications
class ViewController: UIViewController, WKNavigationDelegate {
@IBOutlet var mWebKit: WKWebView!
@IBOutlet var indicator: UIActivityIndicatorView!
public var defaultUrl = "https://www.example.com";
public var viewUrl = URL(string: "https://www.example.com")!
override func viewDidLoad() {
super.viewDidLoad()
mWebKit.navigationDelegate = self
self.mWebKit.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
self.mWebKit.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
loadWebView(viewUrl)
// On Notification Receive
NotificationCenter.default.addObserver(forName: NSNotification.Name("loadWebView"), object: nil, queue: nil) { (Notification) in
//print("notification is \(Notification)")
let url = URL(string: Notification.userInfo?["url"] as? String ?? self.defaultUrl)
self.loadWebView(url ?? self.viewUrl)
}
// Do any additional setup after loading the view, typically from a nib.
}
func loadWebView(_ url: URL) {
var request = URLRequest(url: url)
request.setValue("com.example.in", forHTTPHeaderField: "X-REQUESTED-WITH")
self.mWebKit.load(request)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning();
// Dispose of any resources that can be recreated
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(WKWebView.url) {
indicator.startAnimating()
loadWebView(self.mWebKit.url!)
}
if keyPath == #keyPath(WKWebView.estimatedProgress) {
if(self.mWebKit.estimatedProgress == 1) {
indicator.stopAnimating()
}
}
}
}
在这里,我不是 post 为您的答案提供实际解决方案,而是 post 提供您至少 debug
代码的方式。所以,如果你能够保持断点并且能够看到日志(通过使用打印方法),那么,你可以很容易地找到幕后的真正原因。
这是调试这种情况的方法。
- 转到
edit scheme
- 现在,从左侧菜单中 select
Run
打开的屏幕。现在,SelectInfo
选项卡来自顶部菜单。在这里你会看到Launch
案例的 2 个单选按钮。Automatically
默认会被 select 编辑。将其更改为Wait for executable to be launched
。然后关闭此屏幕。
现在,运行 您的应用在您的设备中。它会在设备上安装您的应用程序,但不会启动您的应用程序,因为它通常每次都会这样做。
现在,post你的推送通知,一旦你收到通知,点击它。当你点击它时,你的应用程序将启动,你的调试会话将开始,如果你的应用程序崩溃,断点将自动停止在那里。否则,如果您的逻辑有任何问题,您可以通过放置断点以及添加 "print" 日志来调试会话,在任何需要的地方。
我认为通过执行以上操作,您将能够进行调试,并且一旦可以调试,您就可以轻松识别问题并找到解决方案。获得解决方案后,将上述设置更改回 Automatically
以正常启动您的应用程序。