UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Day 26. challenge - tasks 1 & 3 - The Great Struggle

Forums > 100 Days of Swift

Hi guys,

I've been struggling whole day with the two tasks from day 26. challenge and you're my last hope.

When it comes to task 1, which particularly is:

"If users try to visit a URL that isn’t allowed, show an alert saying it’s blocked."

What I did here was:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let url = navigationAction.request.url
        let ac = UIAlertController(title: "Page blocked", message: "", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .cancel))
        if let host = url?.host {
            for website in websites {
                if host.contains(website) {
                    decisionHandler(.allow)
                    return
                } else {
                    decisionHandler(.cancel)
                    present(ac, animated: true)
                    return
                }
            }
        }
        decisionHandler(.cancel)
    }

Unfortunately, what this thing does is it shows the alert every time I attempt to enter any other website than the one that initially loaded when the app launched (which, in my instance, is 'apple.com'), no matter what website I try to enter. Maybe the problem comes from the fact that I can't fully grasp what the "host" in the code is and whether it 'contains' a website? I'm just confused.

Task no. 3:

"For more of a challenge, try changing the initial view controller to a table view like in project 1, where users can choose their website from a list rather than just having the first in the array loaded up front."

Oh boy, how much I screwed that one up. I'm totally lost with the relation between the detail view controller and the view controller, I tried to somehow connect them to make it work but I had to scrap everything, as the code started to turn into an array of a million errors. What's surprising though, it didn't pose that much of a problem in Day 23. Milestone. Here, however, it's one big clustertruck. If anyone was willing to share some time to explain what should be done here in a few steps with some important side notes where needed, I would be very grateful.

Have a nice weekend y'all!

4      

Apparently being stubborn enough is all what it takes, cause I solved it :D Of course I'll be more than happy to help if anyone has a similar problem to mine!

4      

Well done! I'd really appreciate if you could help me with the answer also

4      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

I am absolutely having this problem and I can't tell if it's the www. that's tacked on the beginning of "www.apple.com" when it comes back from the host but that can't be it... cause hacking with swift works both ways...

4      

hey @MateusZ I'm super curious how you fixed this? I'm getting the same thing and I can't find the fix for it... our code isn't EXACTLY alike (I don't have the else in my if statement around the decisionHandler but otherwise it's the same)

4      

Call this function right before decisionHandler(.cancel):

func configureAlert() {

      let ac = UIAlertController(title: "Page blocked!", message: nil, preferredStyle: .alert)
      ac.addAction(UIAlertAction(title: "OK", style: .default))

      if webView.isLoading == false {
          present(ac, animated: true)
          return
      }

  }

5      

Hi guys i made this, and works. Hope i can help anyone in the same situation:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let url = navigationAction.request.url

        if let host = url?.host {
            for webSite in webSites {
                if host.contains(webSite) {
                    decisionHandler(.allow)
                    return
                }
            }
        }
        let showUnsecureSiteAlert = UIAlertController(title: "Site not allowed", message: nil, preferredStyle: .alert)
        showUnsecureSiteAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        present(showUnsecureSiteAlert, animated: true)
        decisionHandler(.cancel)
    }

4      

Hey @MateusZ did we need a detailVC for this one?

I was simply trying to change the viewcontroller to a tableviewcontroller, and on table rowdidtap or whatever (sorry im in bed so from memory) compiling the url to open as opposed to doing one hard coded.

Can it not be done this way?

4      

Well... it was rather challenging task to complete (the task 1 at least, the rest two were just fine) because of a small and persisting bug. Strange enough though, as I initially wrote the code by myself as many mentioned here by putting alert controller before decisionHandler(.cancel) but alert persisted dispite i choose a site from allowed list. The result that worked for me, and so far works as expected i.e. if I try to click on links that lead to other sites it denies to open and shows the propert alert, was posted by @abdullatif. You don't really need to write a function though, but simply put that line before decisionHandler(.cancel)

  let deniedAC = UIAlertController(title: "Alert", message: "URL is not allowed.", preferredStyle: .alert)
    deniedAC.addAction(UIAlertAction(title: "Cancel", style: .destructive))

    if !webView.isLoading {
      present(deniedAC, animated: true)
    }
    decisionHandler(.cancel)

Hope it will be useful for someone who is struggling with that task...

4      

Hi all! I have been programming my app without a storyboard. I have a problem with 3 tasks. I created a new UITableViewController and from there passed all the data to the second controller. NavigationController, toolbarItems stopped working on my main controller.

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        guard let windowScene = (scene as? UIWindowScene) else { return }

        let myWindow = UIWindow(windowScene: windowScene)
        let navigationController = UINavigationController()
        let viewController = TableViewController()

        navigationController.viewControllers = [viewController]
        myWindow.rootViewController = navigationController

        self.window = myWindow

        myWindow.makeKeyAndVisible()
    }
}
class TableViewController: UITableViewController {

    private let identifier = "identifier"
    let webSites = ["www.hackingwithswift.com", "www.apple.com", "dyadichev.tilda.ws"]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(UITableViewCell.self,
                           forCellReuseIdentifier: identifier)
        tableView.frame = view.bounds
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        webSites.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier,
                                                 for: indexPath)
        cell.textLabel?.text = webSites[indexPath.row]
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = ViewController()
        vc.selectedSites = webSites[indexPath.row]
        vc.modalPresentationStyle = .fullScreen
        present(vc, animated: true)
    }
}
import UIKit
import WebKit

final class ViewController: UIViewController, WKNavigationDelegate {

    var tableVC = TableViewController()
    var webView: WKWebView!
    var progressView: UIProgressView!
    var selectedSites: String?
//    let webSites = ["www.hackingwithswift.com", "www.apple.com", "dyadichev.tilda.ws"]

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Open",
                                                            style: .plain,
                                                            target: self,
                                                            action: #selector(openTapped))

        let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
                                     target: nil,
                                     action: nil)

        let refresh = UIBarButtonItem(barButtonSystemItem: .refresh,
                                      target: webView,
                                      action: #selector (webView.reload))

        let goBack = UIBarButtonItem(title: "Back",
                                     style: .plain,
                                     target: webView,
                                     action: #selector(webView.goBack))

        let goForward = UIBarButtonItem(title: "Forward",
                                        style: .plain,
                                        target: webView,
                                        action: #selector(webView.goForward))

        progressView = UIProgressView(progressViewStyle: .default)
        progressView.sizeToFit()

        let progressButton = UIBarButtonItem(customView: progressView)

        toolbarItems = [goBack, progressButton, goForward, spacer, refresh]
        navigationController?.isToolbarHidden = false

        webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress),
                            options: .new,
                            context: nil)
        guard let selectSite = selectedSites else {return}
        guard let url = URL(string: "https://" + selectSite) else {return}

        webView.load(URLRequest(url: url))
        webView.allowsBackForwardNavigationGestures = true
    }

    @objc private func openTapped() {

        let ac = UIAlertController(title: "Open page...",
                                   message: nil,
                                   preferredStyle: .actionSheet)

        for webSite in tableVC.webSites {
            ac.addAction(UIAlertAction(title: webSite, style: .default, handler: openPage))
        }

        ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        present(ac, animated: true)
    }

    private func openPage(action: UIAlertAction) {

        guard let actionTitle = action.title else { return }
        guard let url = URL(string: "https://" + (actionTitle)) else { return }

        webView.load(URLRequest(url: url))
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        title = webView.title
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            progressView.progress = Float(webView.estimatedProgress)
        }
    }

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        let url = navigationAction.request.url

        if let host = url?.host {
            for webSite in tableVC.webSites {
                if host.contains(webSite) {
                    decisionHandler(.allow)
                    return
                }
            }
        }
        let ac = UIAlertController(title: "Ошибка",
                                   message: "Данный сайт заблокирован",
                                   preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "Закрыть", style: .cancel))
        if !webView.isLoading {
            present(ac, animated: true)
        }
        decisionHandler(.cancel)
    }
}

3      

Challenge 1

I was actually having an issue trying to figure out how to get an alert to pop up since all of the links on the HWS and Apple page seemed to work fine. Maybe this will help.

I added google.com to the list of accepted websites var websites = ["apple.com", "hackingwithswift.com", "google.com"]

Once on google perform a search for something and then try selecting a search result.

For the alert, I created an alert function and then called it just before the decisionHandler.

This seemed to work for me.

     }

        showAlert()

        decisionHandler(.cancel)
    }

    func showAlert() {
        let alert = UIAlertController(title: "Alert", message: "This website is not for you!!", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Cancel", style: .destructive))

        if !webView.isLoading {
            present(alert, animated: true)
        }
    }
}

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.