Sajjad Ali
Sajjad Ali

Reputation: 23

Accessing wkwebview's backForwardList.backList or backForwardList.forwardList for second time causes crash

I'm trying to access wkWebview's backList, I've written the code below to find it. The code below works fine whenever I'm trying to access it for the first time, but when I again try to access wkwebview's backlist for second time I get a crash of bad access with the code: EXC_I386_GPFLT

Below is my code which I've written:

let backList = webView.backForwardList.backList
let count = backList.count
for item in backList[0..<count] {
    print(item.title)
}

I get the crash at the first line. Can anyone please guide me what can be the cause of crash?

Upvotes: 0

Views: 477

Answers (2)

devshok
devshok

Reputation: 836

By doing this:

let backList = webView.backForwardList.backList

You are creating one more strong reference to backList inside backForwardList and it means that you take a risk to address a memory cell that is not allocated because backList might be changed while you're doing this:

backList[0..<count]

Because WKBackForwardList is a reference-type object that might be modified in any other places at the same time. It's your own business how to deal with it but the most standard way to solve the problem is copying using copy method to avoid the error like yours.

For example:

import os

let copiedList = self.yourWebView
    .backForwardList
    .backList
    .compactMap {
        $0.copy() as? WKBackForwardListItem
    }

let logger = Logger()
        
for item in copiedList {
    logger.info("title: \(item.title)")
    logger.info("url: \(item.url)")
}

Upvotes: 0

Damarendra
Damarendra

Reputation: 26

have you tried something like this

for page in webView.backForwardList.backList {
    print("User visited \(page.title) \(page.url.absoluteString)")
}

Upvotes: 1

Related Questions