How can I show the user an alert if they visit https://google.com
, https://duckduckgo.com
, https://bing.com
or https://yandex.ru
, but don't show anything when they visit any other website?
I have tried this, but no success. (This is just a part of my code)
var isSearchEngine="NO"
if urlString!.contains("https://google.com") {
var isSearchEngine="YES"
} else {
var isSearchEngine="NO"
}
if urlString!.contains("https://duckduckgo.com") {
var isSearchEngine="YES"
} else {
var isSearchEngine="NO"
}
if urlString!.contains("https://yandex.ru") {
var isSearchEngine="YES"
} else {
var isSearchEngine="NO"
}
if urlString!.contains("https://bing.com") {
var isSearchEngine="YES"
} else {
var isSearchEngine="NO"
}
if isHub=="YES" {
Debug.log("Visited search engine website.")
let alert = UIAlertController(title: "Search Engine Detected", message: "The website you visited is a search engine.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true)
} else {
Debug.log("Didn't visit a Search engine website.")
let alert = UIAlertController(title: "No search engine", message: "The website you visited isn't a search engine.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
Every time I run my app with this code, I always get the "No Search Engine" alert, no matter what website I visit. Always "No search engine". Can anyone help me? Many thanks in advance!
Your code does not make sense as written. It executes a series of if/else expressions one after the other. If the URL contains "https://google.com" for example, the first if/else statement would set isSearchEngine
to true, and then the very next if/else statement would set it back to false.
Rewrite it. Something like this would work:
var isSearchEngine = false
if let notNilURLString = urlString {
let searchEngineURLs = [
"https://google.com",
"https://yandex.ru",
"https://duckduckgo.com"] // And so on
for searchEngineURL in searchEngineURLs {
if notNilURLString.contains(searchEngineURL)
isSearchEngine = true
}
}
}
Second problem: After trying to set isSearchEngine = true
when you detect the URL for a search engine, the rest of your code goes on to check if a string isHub=="YES", completely ignoring the value of isSearchEngine
.
Third point: Use the Bool
type for true/false, not strings containing "YES" and "NO".