当应用程序通过推送通知从终止状态打开时,iOS Web View 应用程序崩溃

标签 ios swift wkwebview

当通过推送通知 从终止状态打开时,我的应用程序崩溃了。如果应用程序已经启动,它会很好用,但是当应用程序被终止时,如果收到任何推送通知并且我点击它,它会使应用程序崩溃。我没有发现任何错误,任何人都可以帮我解决这个问题吗?

如果我在 AppDelegate.swift 中评论来自 didFinishLaunchingWithOptionsUNUserNotificationCenter 代码,那么应用程序不会崩溃,但不会针对通知加载 View 。我在推送通知中发送 url 并检查它是否为空,然后将其加载为 View 。

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", $0) }.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()
            }
        }
    }

}

最佳答案

在这里,我不会为您的答案发布实际的解决方案,而是发布您至少可以调试您的代码的方式。所以,如果你能够保持断点并且能够看到日志(通过使用打印方法),那么,你可以很容易地找到幕后的真正原因。

这是调试这种情况的方法。

  1. 转到编辑方案

enter image description here

  1. 现在,打开屏幕,从左侧菜单中选择Run。现在,从顶部菜单中选择 Info 选项卡。在这里您将看到 2 个用于 Launch 案例的单选按钮。 Automatically 将默认选中。将其更改为 Wait for executable to be launched。然后关闭此屏幕。

enter image description here

  1. 现在,在您的设备上运行您的应用程序。它会在设备上安装您的应用程序,但不会启动您的应用程序,因为它通常每次都会这样做。

  2. 现在,发布您的推送通知,一旦您收到通知,请点击它。当你点击它时,你的应用程序将启动,你的调试 session 将开始,如果你的应用程序崩溃,断点将自动停止在那里。否则,如果您的逻辑有任何问题,您可以根据需要通过设置断点和添加“打印”日志来调试 session 。

我认为通过执行上述操作,您将能够进行调试,并且一旦可以调试,您就可以轻松识别问题并找到解决方案。找到解决方案后,将上述设置改回 Automatically 以正常启动您的应用程序。

关于当应用程序通过推送通知从终止状态打开时,iOS Web View 应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53814166/

相关文章:

ios - UITextView 表示它在不存在时为空

ios - 尝试在导航 Controller 之上呈现导航 Controller "Whose view is not in the window hierarchy"

ios - SKPhysicsBody 看起来很小

swift - 如何快速计算struct的字节和

ios - WKWebView 添加为 Subview 不会在 Swift 中旋转时调整大小

ios - 在 IOS 中检查 WKWebView 中的下拉列表

iphone - iOS 崩溃报告 "Hardware Model"到底是什么意思?

iphone - iOS开发: How can I make my view transition to the right instead of to the default left?

ios - 带有第一个字符的 NSPredicate 过滤器数组

swift - 为 TableView 启用 3D Touch 预览