iosswiftxcode3dtouch

Peek-and-Pop UIView to show SFSafariViewController


I have a UITableView and in each cell theres a UIView added as subview. What I currently have is a UITapGestureRecognizer to open the In-App-Safari whenever I click one of those UIViews. However I'm struggling to implement Apples sample code of the peek and pop feature for force touch. My code looks as follows:

 @IBOutlet var mainTableView: UITableView!

in viewDidLoad():

 registerForPreviewing(with: self as! UIViewControllerPreviewingDelegate, sourceView: mainTableView)

after viewDidLoad():

 func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
            // First, get the index path and view for the previewed cell.
        guard let indexPath = tableView.indexPathForRow(at: location),
              let cell = tableView.cellForRow(at: indexPath)
              else { return nil }

 //Enable blurring of other UI elements, and a zoom in animation while peeking.

 previewingContext.sourceRect = cell.frame

 //Create and configure an instance of the color item view controller to show for the peek.

 guard let url = someURL else { return nil }
            let vc = SFSafariViewController(url: url)
            vc.delegate = self as SFSafariViewControllerDelegate

            return vc
        }

        func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) 
{

//Push the configured view controller onto the navigation stack.

 navigationController?.pushViewController(viewControllerToCommit, animated: true)
}

Xcode returns errors such as

Received memory pressure event 4 vm pressure 1

and

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController previewingContext:viewControllerForLocation:]: unrecognized selector sent to instance

I haven't found a solution yet to peek and pop web content when pressing a UIView.


Solution

  • Ok, so i found out that I simply forgot to add UIViewControllerPreviewingDelegate to my class:

    class MyViewController: UITableViewController, UIViewControllerPreviewingDelegate, SFSafariViewControllerDelegate
    

    The peek works as intended with the stated method, but for the pop to work I had to adapt my last function:

        func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
        show(viewControllerToCommit, sender: self)
    }